用位运算的方法;相似的方法可考虑bool数组的方法
设一个int 类型的 mask参数,判断每个字符离'a'的距离,通过左移运算符 '<<' 与1 判断是否出现过,如果出现过,则判断中的值为1,返回false;如果是第一次出现则或运算 '|' 将此位置设置为1。
class Solution {
public:
bool isUnique(string astr) {
int mask = 0;
int step = 0;
for(char cr : astr){
step = cr - int('a');
if(mask & (1<<step)){
return false;
}
else{
mask |= (1<<step);
}
}
return true;
}
};