我写了一个方法来检查一个字符串是否只有唯一的字符.我发送明显的非唯一字符串“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<Boolean,Character> tab = new HashMap<Boolean,Character>(); 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<Character,Boolean> tab = new HashMap<Character,Boolean>(); 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<Character> set = new HashSet<Character>(); 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;