首页 > 其他 > 详细

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

时间:2020-04-04 22:58:34      阅读:66      评论:0      收藏:0      [点我收藏+]

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 }

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

原文:https://www.cnblogs.com/hi3254014978/p/12634009.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!