码迷,mamicode.com
首页 > 其他好文 > 详细

字符流中第一个不重复的字符

时间:2018-02-02 14:30:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:body   string   ==   没有   log   one   void   appear   ring   

题目描述

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

输出描述:

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

思路:一个数组记录下当前字符流,一个哈希表记录下每个字符出现的次数。插入的时间复杂度是O(1), 查找的时间复杂度是O(n)
 1 class Solution
 2 {
 3 public:
 4     Solution()
 5     {
 6         for(int idx=0; idx<128; ++idx)hash[idx]=0;
 7     }
 8   //Insert one char from stringstream
 9     void Insert(char ch)
10     {
11         arr.push_back(ch);
12         int idx=ch-\0;
13         ++hash[idx];
14     }
15   //return the first appearence once char in current stringstream
16     char FirstAppearingOnce()
17     {
18         for(int i=0; i<arr.size(); ++i)
19         {
20             int idx=arr[i]-\0;
21             if(hash[idx]==1)return arr[i];
22         }
23         return #;
24     }
25 private:
26     vector<char> arr;
27     int hash[128];
28 };

 

字符流中第一个不重复的字符

标签:body   string   ==   没有   log   one   void   appear   ring   

原文地址:https://www.cnblogs.com/jeysin/p/8404590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!