共計 783 個字符,預計需要花費 2 分鐘才能閱讀完成。
要找出重復的字符串,可以使用 HashMap 來記錄每個字符串出現的次數。
具體步驟如下:
- 創建一個 HashMap 對象,鍵為字符串,值為該字符串在輸入中出現的次數。
- 遍歷輸入的字符串數組或列表。
- 對于每個字符串,檢查它是否已經在 HashMap 中存在。
- 如果存在,則將該字符串的次數加 1。
- 如果不存在,則將該字符串作為鍵加入 HashMap,并將其次數設置為 1。
- 最后,遍歷 HashMap 的所有鍵值對,找到出現次數大于 1 的字符串,即為重復的字符串。
以下是一個示例代碼:
import java.util.HashMap;
import java.util.Map;
public class FindDuplicateStrings {public static void main(String[] args) {String[] strings = {"hello", "world", "hello", "java", "world"};
Map<String, Integer> stringCountMap = new HashMap<>();
for (String str : strings) {if (stringCountMap.containsKey(str)) {int count = stringCountMap.get(str);
stringCountMap.put(str, count + 1);
} else {stringCountMap.put(str, 1);
}
}
for (Map.Entry<String, Integer> entry : stringCountMap.entrySet()) {if (entry.getValue() > 1) {System.out.println(" 重復字符串:" + entry.getKey());
}
}
}
}
執行以上代碼,輸出結果為:
重復字符串:hello
重復字符串:world
丸趣 TV 網 – 提供最優質的資源集合!
正文完