【剑指Offer】55、字符流中第一个不重复的字符

题目描述

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

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。
题解一:HashMap
 1 private static HashMap<Character, Integer> map=new HashMap();
 2     private static ArrayList<Character> list=new ArrayList<Character>();
 3 //Insert one char from stringstream
 4     public static void Insert(char ch) {
 5         if(map.containsKey(ch)){
 6             map.put(ch,1+map.get(ch));
 7         }else {
 8             map.put(ch,1);
 9         }
10         list.add(ch);
11     }
12     //return the first appearence once char in current stringstream
13     public static char FirstAppearingOnce() {
14         char end='#';
15         for(char key : list){
16             if(map.get(key)==1){
17                 end=key;
18                 break;
19             }
20         }
21         return end;
22     }
题解二:hash表
 1 //一个字符占8位,因此不会超过256个,可以申请一个256大小的数组来实现一个简易的哈希表
 2     private static int[] hashtable=new int[256];
 3     static StringBuffer s=new StringBuffer();
 4     //Insert one char from stringstream
 5     public static void Insert01(char ch) {
 6         s.append(ch);
 7         hashtable[ch]+=1;
 8     }
 9     //return the first appearence once char in current stringstream
10     public static char FirstAppearingOnce01() {
11         char[] str=s.toString().toCharArray();
12         for(char c:str) {
13             if(hashtable[c]==1)
14                 return c;
15         }
16         return '#';
17     }

测试:

 1 public static void main(String[] args) {
 2         String str="helloworld";
 3         char[] chars = str.toCharArray();
 4         for (char aChar : chars) {
 5            Insert(aChar);
 6             char c = FirstAppearingOnce();
 7             System.out.print(c);
 8         }
 9     }
10 输出:hhhhhhhhhh

猜你喜欢

转载自www.cnblogs.com/Blog-cpc/p/12482783.html