2 回答

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

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試使用 1 個(gè)HashMap而不是 2 個(gè) for 循環(huán),如下所示
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());
}
}
}
在這種情況下,每次出現(xiàn)重復(fù)時(shí)都會(huì)打印最后一條語(yǔ)句,您可以根據(jù)需要對(duì)其進(jìn)行修改。
添加回答
舉報(bào)