字符流中出现的第一个字符

 1 package algorithms;
 2 
 3 import java.util.HashMap;
 4 
 5 public class FirstAppearingOnce {
 6     HashMap<Character,Integer> hm = new HashMap<>();
 7     StringBuffer sb = new StringBuffer();
 8     //Insert one char from stringstream
 9     public void Insert(char ch)
10     {
11         if(hm.containsKey(ch)) {
12             hm.put(ch, hm.get(ch)+1);
13         }else {
14             hm.put(ch, 1);
15         }
16         sb.append(ch);
17     }
18   //return the first appearence once char in current stringstream
19     public char FirstAppearingOnce_1()
20     {
21         char[] str = sb.toString().toCharArray();
22         for(int i=0;i<str.length;i++) {
23             if(hm.get(str[i])==1) {
24                 return str[i];
25             }
26         }
27         return '#';
28     }
29 }

其实也可以自己实现一个简易的hashmap用来解决该道题

因为char(8位)有256种取值  所以可以创建一个长度为256的数组  数组的下标即为ascii码值  数组的值即为出现的次数,如下所示:

int[] arr = new int[256];
    StringBuffer s = new StringBuffer();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        s.append(ch);
        arr[ch] +=1;
    }

 

posted @ 2019-03-31 12:14  Practical  阅读(158)  评论(0编辑  收藏  举报