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
本文介绍了一种算法,用于判断一个字符串是否包含所有唯一的字符。通过两种方法实现:一种是使用双重循环进行遍历比较,时间复杂度为O(n^2);另一种是利用HashSet避免重复元素,效率更高。
736

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



