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

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

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

 

 1 import java.util.LinkedHashMap;
 2 import java.util.Map;
 3 public class Solution {
 4     public LinkedHashMap<Character,Integer>  map = new LinkedHashMap<Character,Integer>();
 5     //Insert one char from stringstream
 6     public void Insert(char ch){
 7         if(map.containsKey(ch)){//map中已经有该字符串记录,将旧记录+1
 8             map.put(ch, map.get(ch) + 1);
 9         }else{//map中没有该字符串记录,则新建记录
10             map.put(ch, 1);
11         }
12     }
13     
14     //return the first appearence once char in current stringstream
15     public char FirstAppearingOnce(){
16         //遍历HashMap的方法:通过Map.entrySet遍历key和value
17         //使用该方法,要先import java.util.Map;
18         for (Map.Entry<Character, Integer> set : map.entrySet()) {
19             if (set.getValue() == 1) {
20                 return set.getKey();
21             }
22         }
23         return '#';
24     }
25 }

 

posted @ 2019-07-19 11:16  淡如水94  阅读(140)  评论(0)    收藏  举报