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

转自https://www.cnblogs.com/AndyJee/p/4703171.html

题目描述

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

输出描述:

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

解法1:哈希表统计字符流中每个字符出现的次数(或者应用关联容器 map

通过哈希表统计字符流中每个字符出现的次数,顺便将字符流保存在string中,然后再遍历string,从哈希表中找到第一个出现一次的字符。

#include<iostream>
class Solution
{
private:
    string str;
    int count[256] = {0};
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
         str += ch;
         count[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        int len = str.size();
        for(int i = 0; i < len; i++)
        {
            if(count[str[i]] == 1)
                return str[i];
        }
        return '#';
    }

};

解法2:哈希表特殊处理

链接:https://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720
来源:牛客网
 

利用一个int型数组表示256个字符,这个数组初值置为-1.

每读出一个字符,将该字符的位置存入字符对应数组下标中。

若值为-1表示第一次读入,不为-1表示不是第一次读入,将值改为-2.

之后在数组中找到>0的最小值,该数组下标对应的字符为所求。

#include<iostream>
class Solution
{
private:
    int index = 0;
    int count[256];
public:
    Solution(){
        for(int i=0;i<256;i++){
            count[i] = -1;
        }
        index = 0;
    }
  //Insert one char from stringstream
    void Insert(char ch)
    {
        if(count[ch] == -1)
            count[ch] = index;
        else
            count[ch] = -2;
        ++index;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        char ch = '\0';
        int minIndex=numeric_limits<int>::max();
        for(int i=0;i<256;i++){
            if(count[i]>=0 && count[i]<minIndex)
            {
                ch = char(i);
                minIndex = count[i];
            }
        }
        if(ch == '\0')
            return '#';
        else
            return ch;
    }

};

猜你喜欢

转载自blog.csdn.net/Eartha1995/article/details/81509811