题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
字符流:像流水一样的字符,一去不复返,意味着只能访问一次。
将字符流保存起来,可以用字符串保存,也可以用字符数组保存(vector<char>)
通过哈希表统计字符流中每个字符出现的次数,顺便将字符流保存在vector<char>中,然后再遍历vector<char>,从哈希表中找到第一个出现一次的字符;
这里的哈希表的哈希函数:hash(ch) = ch 字符其本身也是一个整数值
class Solution
{
private:
vector<char> c;
int count[256] = {0};
public:
//Insert one char from stringstream
void Insert(char ch)
{
c.push_back(ch);
//记录字符ch出现的次数
count[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
vector<char>::iterator itr = c.begin();
while(itr < c.end()){
if(count[*itr] == 1)
return *itr;
itr++;
}
return '#';
}
};