AcWing 64. 字符流中第一个只出现一次的字符--Java
原题链接
困难
作者:
Fant.J
,
2019-06-09 17:45:46
,
所有人可见
,
阅读 731
class Solution {
//Insert one char from stringstream
// 记录ch出现的次数
private Map<Character, Integer> count = new HashMap<>();
// 队列
private Queue<Character> queue = new LinkedList<>();
public void insert(char ch){
if(count.containsKey(ch)){
int value = count.get(ch);
count.put(ch, ++value);
}else{
count.put(ch, 1);
}
queue.offer(ch);
// 队列不为空 && 队首字符次数>1 , 则弹出对首
while(!queue.isEmpty() && count.get(queue.peek()) > 1){
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char firstAppearingOnce(){
return queue.isEmpty() ? '#':queue.peek();
}
}