【剑指offer】字符流中第一个不重复的字符(字符串)

版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88600844

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

链接

https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

代码

class Solution
{
public:
    //Insert one char from stringstream
    void Insert(char ch)
    {
        count[ch]++;
        if(index[ch] == 0){
            index[ch] = int(s.length());
        }
        s = s + ch;
    }
    //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        bool flag = false;
        int ans = 1000000000;
        for(int i = 0; i < 300; i++){
            if(count[i] == 1){
                flag = true;
                if(ans > index[i]){
                    ans = index[i];
                }
            }
        }
        if(flag){
            return s[ans];
        }
        else{
            return '#';
        }
    }
    int count[300] = {0}; // 用于记录每个字符出现的次数
    int index[300] = {0}; // 用于记录每个字符第一次出现的下标,下标从1开始
    string s = " ";
};

猜你喜欢

转载自blog.csdn.net/u013095333/article/details/88600844