题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
我的思路
对我来说本题的关键在于没有读懂题意,根据题目,字符流是要挨个读进去的,因此有一个函数insert用来把字符读入字符串中;可以定义一个map<char,int> cha,int 为该字符出现的次数,每插入一个字符,cha[char]++;在函数中判断如果cha[char]==1的话,则只出现了一次,返回该字符。
代码
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch) {
str+=ch;
cha[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce() {
for(auto a:str){
if(cha[a]==1) return a;
}
return '#';
}
private:
string str;
map<char,int> cha;
};