我写了一个方法来检查一个字符串是否只有唯一的字符.我发送明显的非唯一字符串“11”,它返回true而不是false.这是因为在if(tab.get(c)== null)中的get(c)中返回null,即使字符“1”已经在HashMap中.
我该怎么做才能获得预期的行为?
/* Check if a string contains only unique characters */
public static boolean isUniqueChars(String s) {
HashMap tab = new HashMap();
Character c;
for (int i = 0; i < s.length(); ++i) {
c = new Character(s.charAt(i));
if (tab.get(c) == null)
tab.put(Boolean.TRUE, c);
else
return false;
}
return true;
}
public static void main(String[] args) {
String s = "11";
System.out.println(isUniqueChars(s)); /* prints true! why?! */
}
解决方法:
你是按角色取物,但地图的键是布尔值.您希望键为Character,值为Boolean:
HashMap tab = new HashMap();
Character c;
for (int i = 0; i < s.length(); ++i) {
c = new Character(s.charAt(i));
if (tab.get(c) == null)
tab.put(c, Boolean.TRUE);
else
return false;
}
return true;
话说回来:
>您无需显式创建新角色.拳击会为你做到这一点.
>使用HashSet< Character>跟踪你到目前为止看到的角色会更简单.
例如:
Set set = new HashSet();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
// add returns true if the element was added (i.e. it's new) and false
// otherwise (we've seen this character before)
if (!set.add(c)) {
return false;
}
}
return true;
标签:java,hashmap
来源: https://codeday.me/bug/20190715/1467879.html
博客内容讲述了在Java中检查字符串是否包含唯一字符时遇到的问题。原始代码使用HashMap存储字符,但在判断字符是否已存在时出现错误。解决方案是将HashMap的键设置为Character,值为Boolean,正确地检查字符是否已存在于映射中。此外,还提出了使用HashSet作为更简洁的实现方式。

1008

被折叠的 条评论
为什么被折叠?



