剑指Offer-字符流中第一个不重复的字符

字符流中第一个不重复的字符

题目

请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。
当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

思路

思路:开辟一个256的数组  每个字符作为下标   
第一次放的话肯定是index 如果不是第一次就是-2取得时候index>0

代码

public class FirstAppearingOnce {
    int index = 0;
    int[] occurence = new int[256];

    public FirstAppearingOnce() {
        for (int i = 0; i < occurence.leangth; i++) {
            occurence[i] = -1;
        }
    }
    public void insert(char ch){
        if (ch>255){
            return;
        }
        if (occurence[ch]==-1){
            occurence[ch] = index;
        }else {
            occurence[ch] = -2;
        }
        index++;
    }

    public char FirstAppearingOnce(){

        char ch = '\0';

        int minIndex = Integer.MAX_VALUE;
        for (int i=0;i<occurence.length;i++){
            if (occurence[i]>=0&&occurence[i]<minIndex){//minIndex就是保证访问次序的s
                ch = (char) i;
                minIndex = occurence[i];
            }
        }
        if (ch=='\0') return '#';
        return ch;
    }
}
0%