字符流中第一个不重复的字符
字符流中第一个不重复的字符
http://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720
队列:空间O(1),时间O(1)
import java.util.*; public class Solution { //Map<Character,Integer> map = new LinkedHashMap<>(); //Insert one char from stringstream int[] nums = new int[128]; Queue<Character> queue = new LinkedList<>(); public void Insert(char ch) { if(nums[ch]++ == 0){ queue.add(ch); } } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { while(!queue.isEmpty()){ if(nums[queue.peek()]==1) return queue.peek(); else queue.remove(); } return '#'; } }
LinkedHashMap:空间O(N),时间O(1)
import java.util.*; public class Solution { Map<Character,Integer> map = new LinkedHashMap<>(); //Insert one char from stringstream public void Insert(char ch) { if(map.containsKey(ch)) map.put(ch,map.get(ch)+1); else map.put(ch,1); } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { for(char ch:map.keySet()){ if(map.get(ch)==1) return ch; } return '#'; } }