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

版权声明:所有的博客都是个人笔记,交流可以留言。未经允许,谢绝转载。。。 https://blog.csdn.net/qq_35976351/article/details/88378136

题目描述

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

解题思路

利用下标进行映射即可。

AC代码

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        str += ch;
        count[static_cast<int>(ch)]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for (const auto& ch: str) {
            if (count[static_cast<int>(ch)] == 1) {
                return static_cast<int>(ch);
            }
        }
        return '#';
    }
    
    std::string str;
    int count[257] = { 0 };
};

下面这个代码理论上也是对的,而且时空复杂度在常数级别上来说一般更小,但是无法通过,原因不详。。

class Solution
{
public:
    //Insert one char from stringstream
    void Insert(char ch)
    {
        int n = static_cast<int>(ch);
        ++counts[n];
        if (counts[n] == 1) {
            first[n] = MAX;
            ++MAX;
        }
    }
    //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        int best = -1;
        int m = 100000000;
        for (int i = 0; i < 257; ++i) {
            if (counts[i] == 1 && m > first[i]) {
                best = i;
                m = first[i];
            }
        }

        if (best > 0) {
            return static_cast<char>(best);
        }
        else {
            return '#';
        }
    }
    int counts[257] = { 0 };  // 每个字符出现的次数
    int first[257] = { 0 };   // 第一次出现时的计数
    int MAX{ 0 };
};

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/88378136