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

来源:互联网 发布:网络使用管理规定 编辑:程序博客网 时间:2024/06/05 08:10

题目:

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

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

思路:

运用hash表的思想,首先初始化一个长度为256的int型数组,初值为0;以字符的值为下标进行赋值,如果出现一次,就赋值为字符在字符流中的位置。如果出现了第二次甚至更多次,则赋值为-1。然后找到数组中大于0的且最小的数字即为第一次出现一次的字符。

代码:

public class Solution {    public boolean isJing = false;//是否是输入#的标志位    public int[] charIndex = new int[256];    public int index = 1;    //Insert one char from stringstream    public void Insert(char ch)    {        if(charIndex[ch] == 0){            charIndex[ch] = index;        }else if(charIndex[ch] > 0){            charIndex[ch] = -1;        }        index ++;    }  //return the first appearence once char in current stringstream    public char FirstAppearingOnce()    {        char result = '\0';        int minIndex = Integer.MAX_VALUE;        for(int i = 0; i < 256;++i){            if(charIndex[i]>0 && charIndex[i] < minIndex){                result = (char) i;                minIndex = charIndex[i];            }        }        if(result == '#'){            isJing = true;            return result;        }else if(result == '\0'){            return '#';        }        return result;    }