Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
Example 1:
Input: s = "leetcode"
Output: false
Example 2:
Input: s = "abc"
Output: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-unique-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
哈希表思想
java数组实现
class Solution {
public boolean isUnique(String astr) {
boolean[] num = new boolean[26];
Arrays.fill(num,true);
for(int i = 0;i < astr.length();i++){
if (num[astr.charAt(i)-'a'] == true){
num[astr.charAt(i)-'a'] = false;
}else{
return false;
}
}
return true;
}
}
优化 用int 的 26位 进行存储
class Solution {
public boolean isUnique(String astr) {
int mark = 0;
for(int i = 0;i < astr.length();i++){
int bit = 1 << (astr.charAt(i) - 'a');
if ((mark & bit) == 0) {
mark |= bit;
} else {
return false;
}
}
return true;
}
}
其他思路 用哈希map
class Solution {
public boolean isUnique(String astr) {
Set set = new HashSet();
for (int i = 0; i <astr.length() ; i++) {
set.add(astr.charAt(i));
}
return set.size() == astr.length();
}
}
作者:evelynnnnn
链接:https://leetcode-cn.com/problems/is-unique-lcci/solution/javali-yong-setqu-zhong-by-evelynnnnn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。