剑指offer-54-字符流中第一个不重复的字符
字符流中第一个不重复的字符
http://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720
思路
队列存储字符流,如果队首出现的次数大于0,出队,insert直接入队。队列为空输出‘#’
为了快速查询字符出现的次数,可以用数组存储,128是常见字符,256是全部字符,保险起见最好是256;
代码
import java.util.*; public class Solution { //字符出现次数 private int[] c=new int[128]; //字符流缓冲区 private Queue<Character> q=new LinkedList<>(); //Insert one char from stringstream public void Insert(char ch) { c[ch]++; q.offer(ch); } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { while(!q.isEmpty()){ if(c[q.peek()]==1){ return q.peek(); }else{ q.poll(); } } return '#'; } }
剑指offer与数据结构 文章被收录于专栏
本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构