2 回答

TA貢獻1872條經驗 獲得超4個贊
將增量移動到counter此處應該可以:
if (count > 1 && !words[i].equals("0")) {
? ? counter++;
? ? System.out.println(words[i]);
}
而不是在第二個循環中。counter每次您發現另一個重復項時,現在都會增加。counter僅當您發現存在重復單詞時,向下移動才會增加它。
也就是說,可以通過使用Map來計算每個單詞出現的次數來簡化此方法。

TA貢獻1811條經驗 獲得超4個贊
嘗試使用 1 個HashMap而不是 2 個 for 循環,如下所示
public static void main(String[] args) {
String input = "Big black bug bit a big black dog on his big black nose";
HashMap<String, Integer> dupCount = new HashMap<>();
//Converts the string into lowercase
input = input.toLowerCase();
//Split the string into words using built-in function
String words[] = input.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
if(dupCount.containsKey(words[i])){
int cnt = dupCount.get(words[i]);
cnt = cnt + 1;
dupCount.put(words[i], cnt);
}else{
dupCount.put(words[i], 0);
}
}
for(Map.Entry<String, Integer> test : dupCount.entrySet()){
if(test.getValue() > 1) {
System.out.println("Duplicate words in a given string : " +test.getKey() + " : " + test.getValue());
}
}
}
在這種情況下,每次出現重復時都會打印最后一條語句,您可以根據需要對其進行修改。
添加回答
舉報