剑指offer_字符流中第一个不重复的字符
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
方法一:设置一个HashMap来存储是否重复
然后按序遍历查找是否有重复字符
1 import java.util.*; 2 public class Solution { 3 //Insert one char from stringstream 4 HashMap<Character,Boolean> map = new HashMap<>(); 5 List<Character> list = new ArrayList<>(); 6 public void Insert(char ch) 7 { 8 if(map.containsKey(ch)) map.put(ch,true); 9 else{ 10 map.put(ch,false); 11 list.add(ch); 12 } 13 14 15 } 16 //return the first appearence once char in current stringstream 17 public char FirstAppearingOnce() 18 { 19 for(int i = 0;i<list.size();i++){ 20 if(!map.get(list.get(i))) return list.get(i); 21 } 22 return '#'; 23 } 24 }
方法二:
可以用一个数组存储状态,使用队列存储字符
1 import java.util.*; 2 public class Solution { 3 //Insert one char from stringstream 4 private int[] cnts = new int [256]; 5 private Queue<Character> queue = new LinkedList<>(); 6 public void Insert(char ch) 7 { 8 cnts[ch]++; 9 queue.add(ch); 10 while(!queue.isEmpty()&&cnts[queue.peek()]>1) 11 queue.poll(); 12 13 } 14 //return the first appearence once char in current stringstream 15 public char FirstAppearingOnce() 16 { 17 if(queue.isEmpty()) 18 return '#'; 19 else 20 return queue.peek(); 21 } 22 }

浙公网安备 33010602011771号