使用哈希表和队列,每次输入的字符,哈希表中对应的次数+1,当次数为1时,加入队列;同时将队列首部出现次数大于1的字符全部删除。
import java.util.*;
public class Solution {
//Insert one char from stringstream
Map<Character,Integer> map = new HashMap<>();
Queue<Character> q = new LinkedList<>();
public void Insert(char ch)
{
map.put(ch, map.getOrDefault(ch, 0) + 1);
if(map.get(ch) == 1) {
q.offer(ch);
}
while(q.size() > 0 && map.get(q.peek()) > 1) {
q.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
if(q.size() == 0) {
return '#';
} else {
return q.peek();
}
}
}