题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go""go""go"时,第一个只出现一次的字符是"g""g""g"。当从该字符流中读出前六个字符“google"“google"“google"时,第一个只出现一次的字符是"l""l""l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:对于读入的每个字符,将其存入mapmapmap中,keykeykey为该字符,valuevaluevalue为该字符出现的次数;遍历已经读入的字符串,如果mp[str[i]]==1mp[str[i]] == 1mp[str[i]]==1,则说明该字符str[i]str[i]str[i]为当前第一个只出现一次的字符
class Solution
{
public:
//Insert one char from stringstream
Solution():index(0) {}
void Insert(char ch)
{
str[index] = ch;
mp[ch]++;
index++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
for (int i = 0; i < index; ++i) {
if (mp[str[i]] == 1)
return str[i];
}
return '#';
}
map<char, int> mp;
string str;
int index;
};