题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
利用一个int型数组表示256个字符,这个数组初值置为-1.
每从字符流读出一个字符,将该字符的位置存入字符对应数组下标中。
若值为-1表示这是第一次读入,就把对应位置变为该字符在字符串中出现的位置,不为-1且>=0表示不是第一次读入,将值改为-2。
之后在数组中找到大于等于0的数对应的数组下标,该数组下标转换为字符即为所求。同时要把这个该数组的值保存下来,也就是此字符在字符串中出现的位置,等下次再遇到只出现一次的字符时,需要比较他的位置和之前的哪个更小,哪个就是第一个不重复的。
代码如下:
public class Solution {
//Insert one char from stringstream
private int[] occurence = new int[256];
private int index;
public Solution(){
for(int i=0;i<256;i++){
occurence[i] = -1;
}
index = 0;
}
void Insert(char ch)
{
if(occurence[ch] == -1)
occurence[ch] = index;
else if(occurence[ch] >= 0)
occurence[ch] = -2;
index++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
char ch = '\0';
int minIndex = Integer.MAX_VALUE;
for(int i=0;i<256;i++){
if(occurence[i] >=0 && occurence[i]<minIndex){
ch = (char)i;
minIndex = occurence[i];
}
}
if(ch == '\0')
return '#';
return ch;
}
}