剑指offer50.2-AcWing-64. 字符流中第一个只出现一次的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是’g’。
当从该字符流中读出前六个字符”google”时,第一个只出现一次的字符是’l’。
如果当前字符流没有存在出现一次的字符,返回#字符。
样例
输入:"google"
输出:"ggg#ll"
解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。
思路:
用数组vector wordToIndex 存储字符串中每个位置对应的字符.
用unordered_map<char, int> is_show存放该字符串出现的次数.
插入: 在插入的时候不断把字符插入到wordToIndex中,并且如果该字符之前在is_show中出现过则数量++,没有的话则加入到is_show中.
计算第一个: 顺序遍历wordToIndex , 直到找到一个只出现过一次的字符,然后输出.没有的话则直接return ‘#’.
C++ code:
class Solution{
private:
vector<char> wordToIndex;
unordered_map<char, int> is_show;
public:
//Insert one char from stringstream
void insert(char ch){
wordToIndex.push_back(ch);
if(is_show.find(ch) == is_show.end()){
is_show[ch] = 1;
}else{
is_show[ch]++;
}
}
//return the first appearence once char in current stringstream
char firstAppearingOnce(){
for(int i = 0; i < wordToIndex.size(); i++){
if(is_show[wordToIndex[i]] == 1){
return wordToIndex[i];
}
}
return '#';
}
};