概述
題目描述
請實作一個函數用來找出字元流中第一個隻出現一次的字元。例如,當從字元流中隻讀出前兩個字元”go”時,第一個隻出現一次的字元是”g”。當從該字元流中讀出前六個字元“google”時,第一個隻出現一次的字元是”l”。
輸出描述:
如果目前字元流沒有存在出現一次的字元,傳回#字元。
思路
做這一題時,剛開始對題意的了解有所偏差。認為是尋找字元流中第一次出現的不重複的字元,但是本意是線上處理,尋找目前字元流中第一次不重複的字元。
C++ AC代碼
#include <iostream>
#include <map>
#include <queue>
using namespace std;
class Solution
{
private:
map<char,int> Map;
queue<char> letter;
public:
//Insert one char from stringstream
void Insert(char ch){
Map[ch]++;
if(Map[ch] == 1){
letter.push(ch);
}
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce(){
while(!letter.empty() && Map[letter.front()] >= 2){
letter.pop();
}
if(letter.empty()){
return '#';
}else{
return letter.front();
}
}
};
複制