剑指offer 54.字符流中第一个不重复的字符

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

思路:

在插入字符的时候,利用 hash 进行计数排序,查找第一个不重复的字符的时候只需再次遍历原串,判断每个字符在 hash 数组中的值是否为1,如果为1,则直接输出

下面分别使用 Hash 数组 和 HashMap 统计字符出现次数

使用hash 数组

 1 public class Solution {
 2     public StringBuilder str = new StringBuilder();
 3     public int[] hash = new int[256];    // 大小为 256 的数组,计数排序
 4     //Insert one char from stringstream
 5     public void Insert(char ch)
 6     {
 7         str.append(ch);
 8         hash[ch]++;
 9     }
10   //return the first appearence once char in current stringstream
11     public char FirstAppearingOnce()
12     {
13        for(int i = 0; i < str.length(); i++){
14            if(hash[str.charAt(i)] == 1){
15                return str.charAt(i);
16            }
17        }
18         return '#';
19     }
20 }

使用 HashMap

 1 import java.util.HashMap;
 2 import java.util.ArrayList;
 3 public class Solution {
 4     public ArrayList<Character> list = new ArrayList<>();    // 用来记录字符
 5     public HashMap<Character, Integer> hm = new HashMap<>();
 6     //Insert one char from stringstream
 7     public void Insert(char ch)
 8     {
 9         list.add(ch);
10         if(hm.containsKey(ch)){
11             hm.put(ch, hm.get(ch) + 1);
12         }else{
13             hm.put(ch, 1);
14         }
15     }
16   //return the first appearence once char in current stringstream
17     public char FirstAppearingOnce()
18     {
19        for(char ch : list){
20            if(hm.get(ch) == 1){
21                return ch;
22            }
23        }
24         return '#';
25     }
26 }
posted @ 2020-04-04 20:41  Lucky小黄人^_^  阅读(157)  评论(0编辑  收藏  举报