題目
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符”go”時,第一個只出現一次的字符是”g”。當從該字符流中讀出前六個字符“google”時,第一個只出現一次的字符是”l”。如果當前字符流沒有存在出現一次的字符,返回#字符。
思路
用一個128位數組存儲每個字符出現的次數,初始爲0,每當插入一個字符時,當前字符的計數加1,然後判斷當前的計數,如果等於1的話就壓入到隊列裏面去,當要輸出第一個只出現一次的字符時,隊列裏面的元素依次彈出一直到隊首元素目前統計出現的次數爲1爲止。
參考代碼
class Solution
{
public:
Solution()
{
memset(cnt, 0, sizeof(cnt));
}
//Insert one char from stringstream
void Insert(char ch)
{
cnt[ch]++;
if (cnt[ch] == 1)
{
q.push(ch);
}
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
while (!q.empty() && cnt[q.front()] >= 2) q.pop();
if (!q.empty()) return q.front();
else return '#';
}
private:
queue<char> q;
int cnt[128];
};