題目描述:
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"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;
};