gpt4 book ai didi

Java算法来检查字符串中的所有字符是否唯一,不适用于Hashmap?使用 map 运算符是否有更好的解决方案?

转载 作者:行者123 更新时间:2023-12-01 17:56:28 26 4
gpt4 key购买 nike

我有以下代码用于检测字符串中的所有字符是否唯一,如果唯一则返回 true,否则返回 false。为什么我的 map 中的字符增量永远不会超过 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;

}

还有一种更“响应式(Reactive)”的方法来执行此操作,例如对每个字符使用映射运算符来帮助确定是否存在重复字符?

最佳答案

试试这个。

public static boolean hasUniqueChars(String word) {
return word.chars().distinct().count() == word.length();
}

关于Java算法来检查字符串中的所有字符是否唯一,不适用于Hashmap?使用 map 运算符是否有更好的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com