题解 | #第一个只出现一次的字符# 状态 / 位运算
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=188&&tqId=38575&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
时间:O(n)
空间:O(1)
sta: 记录当前字符串的状态flag:如果某个字符出现了两次以上,那么就记录
代码实现:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
long long sta = 0, flag = 0;
for(auto &c : str) {
int x = c - 'a';
if(sta & (1 << x)) flag |= (1 << x); // 标记出现两次及以上的字符串
sta |= (1 << x);
}
for(int i = 0; i < str.size(); i++) {
int x = str[i] - 'a';
if((sta & (1 << x)) && !(flag & (1 << x))) return i; // 只出现一次的字符串
}
return -1;
}
};
小天才公司福利 1192人发布
查看20道真题和解析