字符串处理 哈希
作者:
xianhai
,
2021-11-18 09:16:50
,
所有人可见
,
阅读 240
题1
字符串中第一个只出现一次的字符
class Solution {
public:
char firstNotRepeatingChar(string s) {
unordered_map<char, int> cnt;
for (auto c : s) {
cnt[c]++;
}
char res = '#';
for (auto c : s) {
if (cnt[c] == 1) {
res = c;
break;
}
}
return res;
}
};
题2
字符流中第一个只出现一次的字符
class Solution{
public:
unordered_map<char, int> cnt;
queue<char> q;
//Insert one char from stringstream
void insert(char ch){
cnt[ch]++;
if (cnt[ch] > 1) {
while (q.size() && cnt[q.front()] > 1) {
q.pop();
}
} else {
q.push(ch);
}
}
//return the first appearence once char in current stringstream
char firstAppearingOnce(){
if (q.empty()) {
return '#';
}
return q.front();
}
};