题目描述:
实现一个算法,确定一个字符串s
的所有字符是否全都不同。
示例:
输入: s = "leetcode"
输出: false
输入: s = "abc"
输出: true
限制:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分
更多详细描述,可见官网
解题思路
方法一:将字符串s
转成字符数组,对当前的字符数组存入set
集合中,最后比较set
集合与字符数组的长度是否相等即可。
public boolean isUnique(String astr) {
Set<Character> hashSet = new HashSet<Character>(astr.length());
char[] toCharArray = astr.toCharArray();
for (char c : toCharArray) {
hashSet.add(c);
}
return hashSet.size()==astr.length();
}
方法二:用数组,和方法一类似。(当然,仅考虑字符串包含字母而已)
public boolean isUnique(String astr) {
boolean[] booleans = new boolean[26];
for (int i = 0; i < astr.length(); i++) {
char c = astr.charAt(i);
int temp = (int)c-97;
if (!booleans[temp]){
booleans[temp] = true;
}else {
return false;
}
}
return true;
}
方法三:用位移。说实话,这个一般人真想不到。佩服!!!
public boolean isUnique(String astr) {
int mark = 0;
for (int i = 0; i < astr.length(); i++) {
int move = (int)astr.charAt(i)- 'a';
if ((mark & (1<< move) )!=0){
return false;
}else {
mark |= (1<<move);
}
}
return true;
}