找出字符流中第一个只出现一次的字符

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

 1 class Solution
 2 {
 3 
 4     // 方法一:
 5     #if false
 6     // 字典的键值存放字符和出现的次数
 7     private Dictionary<char, int> dict = new Dictionary<char,int>();
 8 
 9     public char FirstAppearingOnce()
10     {
11         // write code here
12         // 遍历字典,第一个Value为1的Key为所求
13         foreach (var item in dict)
14         {
15             if (item.Value == 1)
16             {
17                 return (char)item.Key;
18             }
19         }
20 
21         return '#';
22     }
23 
24     public void Insert(char c)
25     {
26         // write code here
27         // 字典为空,加入第一个键值
28         if (dict == null)
29         {
30             dict.Add(c, 1);
31             return;
32         }
33 
34         // 字典是否存在键值c,默认false
35         bool flag = false;
36 
37         if (dict.ContainsKey(c))
38         {
39             dict[c] += 1;
40         }
41         else
42         {
43             dict.Add(c, 1);
44         }
45     }
46     #endif
47 
48     // 方法二:
49     /* 申请一个整数数组,大小为256,int[] count = new int[256]{0};
50      * 初始化值全为 0
51      * 以输入字符的值作为数组下标,在对应的位置存入出现次数,
52      * 声明一个字符列表,记录输入字符的顺序         *
53      */
54     private int[] count = new int[256];
55 
56     private List<char> list = new List<char>();
57 
58     public void Insert(char ch)
59     {
60         // Write code here
61 
62         // 如果当前字符第一次出现,记录出现顺序
63         if (count[(int) ch] == 0)
64             list.Add(ch);
65 
66         count[(int) ch]++;
67     }
68 
69     public char FirstAppearingOnce()
70     {
71         // Write code here
72 
73         foreach (var item in list)
74         {
75             if (count[(int) item] == 1)
76             {
77                 return (char) item;
78             }
79         }
80 
81         return '#';
82     }
83 }

猜你喜欢

转载自www.cnblogs.com/xiaolongren/p/12157659.html