题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
解题思路
要利用一个数据结构存储字符出现的顺序,和三种出现状态——一次,多次,未出现。
利用 int 型数组保存字符是否出现。
-
-1 表示没有出现
-
-2 表示出现多次
-
0~inf 表示出现时间
最后找到数组中大于等于 0 但是最小的数字的 index,其 index 对应的 char 就是所求字符。
代码
public class Solution {
private int[] occurence = new int[256];
private int index;
public Solution() {
for (int i = 0; i < occurence.length; i++)
occurence[i] = -1;
index = 0;
}
//Insert one char from stringstream
public void Insert(char ch) {
if (occurence[ch] >= 0)
occurence[ch] = -2;
else if (occurence[ch] == -1)
occurence[ch] = index;
index++;
}
//return the first appearence once char in current stringstream
public 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;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于