用一个数组记录一下各个字符出现次数,然后用队列来存一下上一个走了该由谁来接替,所以的字符进一次出一次队列,所以算法时间复杂度为O(N);
public void Insert(char ch) { //所有字符都在第一次来的时候进队列,换的时候将不为1次的全部弹出 if(++charOccurs[ch]==1){ occurOnes.add(ch); } if(curFirstAppear==null||curFirstAppear==ch){ //换一个 while(!occurOnes.isEmpty()&&charOccurs[occurOnes.peek()]!=1){ occurOnes.poll();//不为1的全弹出去 } curFirstAppear = occurOnes.isEmpty()?null:occurOnes.poll(); } } //return the first appearence once char in current stringstream Queue<Character> occurOnes = new LinkedList<>(); Character curFirstAppear = null; int[] charOccurs = new int[256]; public char FirstAppearingOnce() { return curFirstAppear==null?'#':curFirstAppear; }