Implement an algorithm to determine if a string has all unique characters
Example
Given "abc", return true
Given "aab", return false
遍历:
public boolean isUnique(String str) {
if (str == null || str.length() == 0) {
return true;
}
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
return false;
}
}
}
return true;
}
Set:
public boolean isUnique(String str) {
if (str == null || str.length() == 0) {
return true;
}
HashSet<Character> hashSet = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
if (hashSet.contains(str.charAt(i))) {
return false;
} else {
hashSet.add(str.charAt(i));
}
}
return true;
}
思路
1. O(n^2)遍历
2. Set avoid duplication