[英]Java algorithm to check to detect if all characters in string are unique not working with Hashmap? Is there a better solution using map operators?
我有以下代碼來檢測字符串中的所有字符是否都是唯一的,如果唯一則返回true,否則返回false。 為什么地圖中的字符永遠不會超過1?
public static boolean hasUniqueChars(String word) {
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < word.length(); i++) {
if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
map.put(""+word.charAt(i), 1);
} else {
map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
}
}
Iterator it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if((Integer)pair.getValue() != 1) {
return false;
}
}
return true;
}
還有一種更“主動”的方法來執行此操作,例如對每個字符使用映射運算符來幫助確定是否存在重復字符?
嘗試這個。
public static boolean hasUniqueChars(String word) {
return word.chars().distinct().count() == word.length();
}
仔細查看您的for
循環:
for (int i=0; i < word.length(); i++) {
if (map.get(word.charAt(i)) == null) {
map.put("" + word.charAt(i), 1);
} else {
map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
}
}
您正在使用word.charAt(i)
而不是連接字符串"" + word.charAt(i)
。 嘗試在各處使用一致的鍵,您的問題可能會消失:
if (map.get("" + word.charAt(i)) == null) {
map.put("" + word.charAt(i), 1);
} else {
map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
}
這是一個演示,演示了進行此更改后您的代碼可以按預期工作:
這絕對不是最好的解決方案,但不要忘記Set <>和快速迭代:
public boolean hasUniqueChars(String word) {
Set<Character> characters = new HashSet<>();
for(Character c : word.toCharArray()) {
if(characters.contains(c)) return false;
characters.add(c);
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.