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

非常简洁和巧妙的算法。

时间:O(n)

 1 class Solution
 2 {
 3 public:
 4     //仿照hash表实现,str存储插入的字符,hash[256]存储插入字符的个数
 5     string str;
 6     char hash[256] = {0};
 7     void Insert(char ch)
 8     {
 9         str += ch;
10         hash[ch]++;
11     }
12     
13     //遍历插入的字符(按照插入的顺序,可方便的得到第一个),hash表中个数为1的输出,否则返回#
14     char FirstAppearingOnce()
15     {
16         for(char ch : str)
17             if(hash[ch] == 1)
18                 return ch;
19         return '#';
20     }
21 };

一个函数

 1     //判断第一个出现一次的字符
 2     char findSingle(string str)
 3     {
 4         char hash[256] = {0};
 5         for(char ch : str)
 6             hash[ch]++;
 7         for(char ch : str)
 8             if(hash[ch] == 1)
 9                 return ch;     
10         return '#';   
11     }
原文地址:https://www.cnblogs.com/yocichen/p/11253447.html