Q:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:如果当前字符流没有存在出现一次的字符,返回#字符。
T:
1.用hash。

  //Insert one char from stringstream
    string s;
    char hash[256]={0};
    void Insert(char ch)
    {
        s+=ch;
        hash[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
         
        int size=s.size();
        for(int i=0;i<size;++i)
        {
            if(hash[s[i]]==1)
                return s[i];
        }
        return '#';
    }

2.队列(感谢@txlstars)
(1)用一个128大小的数组统计每个字符出现的次数
(2)用一个队列,如果第一次遇到ch字符,则插入队列;其他情况不再插入
(3)求解第一个出现的字符,判断队首元素是否只出现一次,如果是直接返回,否则删除继续第3步骤

public:
  //Insert one char from stringstream
    void Insert(char ch)
    {  
        ++cnt[ch - '\0'];
        if(cnt[ch - '\0'] == 1)
           data.push(ch);
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
      while(!data.empty() && cnt[data.front()] >= 2) data.pop();
        if(data.empty()) return '#';
        return data.front();
    }
    Solution()
    {
      memset(cnt, 0, sizeof(cnt));    
    }
private:
    queue<char> data;
    unsigned cnt[128];

相关文章:

  • 2021-09-18
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2021-06-20
  • 2022-01-17
  • 2022-01-06
猜你喜欢
  • 2021-12-01
  • 2022-12-23
  • 2022-01-02
  • 2022-01-16
  • 2022-02-19
  • 2022-12-23
  • 2021-11-26
相关资源
相似解决方案