题目描述:
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
完整代码:
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
//将输入进来的字符添加到字符串中
s += ch;
//计算当前的字符在哈希表中的个数
hashtable[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
//计算字符串的长度
int length = s.size();
//遍历整个字符串
for(int i = 0; i < length; ++i)
{
//如果字符在哈希表中已经存在
if(hashtable[s[i]] == 1)
return s[i];
}
//如果没有找到
return '#';
}
private:
//声明一个字符串变量
string s;
//声明一个哈希表变量
map<char, int> hashtable;
};