剑指offer——字符流中第一个不重复的字符

版权声明:本文为博主原创文章,若需转载,请注明http://blog.csdn.net/qq_30091945 https://blog.csdn.net/qq_30091945/article/details/82351604

概述

题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”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();
            }
        }
};

猜你喜欢

转载自blog.csdn.net/qq_30091945/article/details/82351604
今日推荐