题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
返回值描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:该题与之前做过的题有点相似,区别在于这道题是动态的,例如"goole"这个字符串,当读到"go"时,输出"g",当读到"goo",输出"g",读到"goog",输出"#".
运用一个map来记录字符和所出现的次数,一个队列来保存当前所读到的字符,当队首在map中所记录的出现次数>1且队列不为空,则将其进行出队.最后将队首的字符返回.
import java.util.*;
public class Solution {
//Insert one char from stringstream
Map<Character,Integer> map = new HashMap<>();
Queue<Character> queue = new LinkedList<>();
public void Insert(char ch)
{
if(!map.containsKey(ch)){
map.put(ch,1);
}else{
int value = map.get(ch);
map.put(ch,++value);
}
queue.add(ch);
while(!queue.isEmpty() && map.get(queue.peek())>1){
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
return queue.isEmpty()? '#':queue.peek();
}
}