簡體   English   中英

用於檢測字符串中所有字符是否唯一的Java算法不能與Hashmap一起使用嗎? 使用地圖運算符是否有更好的解決方案?

[英]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);
}

這是一個演示,演示了進行此更改后您的代碼可以按預期工作:

Rextester

這絕對不是最好的解決方案,但不要忘記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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM