实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
https://leetcode-cn.com/problems/is-unique-lcci/
示例 1:
输入: s = “leetcode”
输出: false
示例 2:
输入: s = “abc”
输出: true
限制:
- 0 <= len(s) <= 100
- 如果你不使用额外的数据结构,会很加分。
1.使用HashSet
class Solution {
public boolean isUnique(String astr) {
Set<Character> set = new HashSet<>();
for(int i=0; i<astr.length(); i++){
if(set.contains(astr.charAt(i))){
return false;
}
else
set.add(astr.charAt(i));
}
return true;
}
}
2.使用位运算
假设字符串为26个小写字母所组成,int型为4字节,32位,可用作标记
class Solution {
public boolean isUnique(String astr) {
int special = 0;
for(int i=0; i<astr.length(); i++){
int bit = astr.charAt(i)-'a';
if((special&(1<<bit))!=0){
return false;
}else{
special = special|(1<<bit);
}
}
return true;
}
}