没写代码的题,其链接点开都是有代码的。开始前请思考下图:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/30c8893a7609436ab0c167a624baed8d.png)
小试牛刀
class Solution {
public:
int hammingWeight(int n) {
int res = 0;
while (n) {
n &= n - 1;
res++;
}
return res;
}
};
class Solution {
public:
vector<int> countBits(int n) {
vector<int> res(n + 1);
for (int i = 0; i < n + 1; ++i) {
res[i] = count(i);
}
return res;
}
int count(int n) {
int res = 0;
while (n) {
n &= n - 1;
res++;
}
return res;
}
};
进入正题
class Solution {
public:
bool isUnique(string astr) {
if (astr.size() > 26)
return false;
int bit = 0;
for (auto e : astr) {
if (bit >> (e - 'a'))
return false;
else
bit |= 1 << (e - 'a');
}
return true;
}
};