算法思想:哈希+队列
哈希用来统计每个字符出现的个数
队列用来记录字符间的入队顺序
具体代码如下:
import java.util.*;
public class Solution {
//Insert one char from stringstream
//队列
ArrayDeque<Character> dq = new ArrayDeque<>();
//哈希
HashMap<Character,Integer> map = new HashMap<>();
public void Insert(char ch)
{
//判断存不存在
if(!map.containsKey(ch))
map.put(ch,1);
else{
map.put(ch,map.getOrDefault(ch,0)+1);
}
//不管存不存在,都要入队
dq.addLast(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char top = '#';
while(!dq.isEmpty()){
top = dq.peekFirst();//队头元素
if(map.get(top)==1)
return top;
dq.pollFirst();
}
top = '#';
return top;
}
}