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

题目描述

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

思路

Hash:创建数组表示每个字符的出现次数,挨个读入字符后将字符对应数组数字加一,之后遍历字符串,若该字符的出现次数统计为1,则返回

代码

class Solution
{
public:
    string str;
    int Hash[128];
  //Insert one char from stringstream
    void Insert(char ch)
    {
        str = str + ch;
        Hash[ch-NULL]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        if(str.size() == 0)
            return '#';
        for(int i = 0; i < str.size();i++)
        {
            if(Hash[str[i]-NULL] == 1)
                return str[i];
        }
        return '#';
    }
};
发布了85 篇原创文章 · 获赞 0 · 访问量 403

猜你喜欢

转载自blog.csdn.net/weixin_38312163/article/details/104766160