boolean hasAllUniqueChars(String str) {
HashMap<Character, Object> hashMapChars = new HashMap<Character, Object>();
for (int i = 0; i < str.length(); i++) {
if (hashMapChars.containsKey(str.charAt(i))) {
return false;
} else {
hashMapChars.put(str.charAt(i), null);
}
}
return true;
}
The second one is the most trivial one and has time complexity O(n2). It uses two nested for loops:
boolean hasAllUniqueChars2(String str) {
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < str.length(); j++) {
if(i == j){
continue;
}
if(str.charAt(i) == str.charAt(j)){
return false;
}
}
}
return true;
}
why don't you use hashset instead of hashmap?
ReplyDeleteboolean hasAllUniqueChars(String str) {
DeleteHashSet collection = new HashMap();
for (int i = 0; i < str.length(); i++) {
if (!collection.add(str.charAt(i))) {
return false;
}
}
return true;
}
Ivo, you are absolutely right! HashSet is even better. Thanks!
Delete