剑指offer——64. 字符流中第一个只出现一次的字符
作者:互联网
思路1:在字符流中,我们只记录有贡献的答案,即hash值为1的,大于1的全部舍弃
代码:
class Solution{
public:
//Insert one char from stringstream
queue<char> q;
unordered_map<char,int> hash;
void insert(char ch){
hash[ch]++;
if(hash[ch]>1){
while(q.size()&&hash[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();
}
};
思路2:暴力
代码:
class Solution{
public:
//Insert one char from stringstream
string s;
unordered_map<char,int> hash;
void insert(char ch){
hash[ch]++;
s+=ch;
}
//return the first appearence once char in current stringstream
char firstAppearingOnce(){
for(auto x:s) if(hash[x]==1) return x;
return '#';
}
};
标签:字符,ch,hash,offer,流中,char,stringstream,return 来源: https://blog.csdn.net/qq_43619680/article/details/117162037