Algorithm
class Solution {
// 方法1,通过 set 运算
public boolean isUnique(String astr) {
if (astr == null || astr.length() <= 1) {
return true;
}
Set<Character> set = new HashSet<Character>();
for(int i = 0; i < astr.length(); i++) {
if (set.contains(astr.charAt(i))) {
return false;
} else {
char cur = astr.charAt(i);
set.add(cur);
}
}
return true;
}
//方法2,通过位运算
public boolean isUnique(String astr) {
int len = astr.length();
if (len > 26) {
return false;
}
int num = 0;
for (int i = 0; i < len; i++) {
char c = astr.charAt(i);
int index = c - 'a';
if ((num & (1 << index)) != 0) {
return false;
} else {
num |= 1 << index;
}
}
return true;
}
}
Review
Tip
AndroidStudio看代码一层层点方法调用的时候,再想回到原来的页面,有快捷键可以用:
默认是 command + [ 和 command + ]