剑指offer_编程题_字符流中第一个不重复的字符

  • 题目
    请实现一个函数用来找出字符流中第一个只出现一次的字符。
    例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。
    当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
    
  1. 使用map容器统计各字符出现次数,再遍历字符流获得第一个出现一次的字符
    class Solution
    {
    private:
        std::vector<char> v;
    public:
      //Insert one char from stringstream
        void Insert(char ch)
        {
             v.push_back(ch);
        }
      //return the first appearence once char in current stringstream
        char FirstAppearingOnce()
        {
     	   std::map<char,int> m;
     	   for (int i = 0; i < v.size(); ++i)
     	   {
     		   char ch = v.at(i);
     		   if (m.count(ch)>0) m[ch]++;
     		   else m[ch]=1;
     	   }
     	   for (int i = 0; i < v.size(); ++i)
     	   {
     		   char ch = v.at(i);
     		   if (m[ch]==1) return ch;
     	   }
     	   return '#';
        }
    };
    
  2. char类型被定义为8位的存储类型
    可通过定义28长度的数组散列
    class Solution
    {
    private:
        char* v = new char[256]();
        int now = 1;
    public:
      //Insert one char from stringstream
        void Insert(char ch)
        {
             if (*(v+ch)== 0){
          	   *(v+ch) = now;
          	   now ++;
             } 
             else
          	   *(v+ch) = -1;
        }
      //return the first appearence once char in current stringstream
        char FirstAppearingOnce()
        {
     	   int temp = 257;
     	   char res;
     	   for (int i = 0;i<256;i++){
     		   if (*(v+i)>0&&temp>*(v+i)) {
     			   temp = *(v+i); 
     			   res = i;
     		   }
     	   }
     	   if(temp==257)
     		   return '#';
     	   return res;
        }
    };
    
发布了80 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/C_abua/article/details/105740612