zoukankan      html  css  js  c++  java
  • 剑指offer系列43:字符流中第一个不重复的字符

    前面有一道题跟这个很类似,第35题。有了那个的经验这个就很好做了。区别是这个需要做的是一个字符流的只出现一次的字符,也就是字符串的情况是动态变化的。

    有两个数据结构,一个是string类型的用来存储当前的字符流,还有一个用数组表示的哈希表来存储各个字符出现的次数。找第一个只出现一次的字符就是找哈希表中第一个值为1的字符。

     1 class Solution
     2 {
     3 public:
     4     Solution()//构造函数给私有成员赋初值
     5     {
     6         str = "";
     7         for (int i = 0; i < 256; i++)
     8         {
     9             count[i] = 0;
    10         }
    11     }
    12     //Insert one char from stringstream
    13     void Insert(char ch)
    14     {
    15         str += ch;
    16         count[int (ch)]++;
    17     }
    18     //return the first appearence once char in current stringstream
    19     char FirstAppearingOnce()
    20     {
    21         int len = str.size();
    22         for (int i = 0; i < len; i++)
    23         {
    24             //cout << int(str[i]) << endl;
    25             if (count[int(str[i])] == 1)
    26                 return char(str[i]);
    27         }
    28         return '#';
    29     }
    30 private:
    31     string str;
    32     int count[256];
    33 };
  • 相关阅读:
    cocos2d-x把json数据解析到数组或字典中(libjson库)
    (bug更正)利用KVC和associative特性在NSObject中存储键值
    第二次博客作业
    我的感想
    期末总结
    陈老师作业
    第三次作业---四则运算的进一步完善
    好难
    对git的认识
    计应143 卞玉新
  • 原文地址:https://www.cnblogs.com/neverland0718/p/11244105.html
Copyright © 2011-2022 走看看