题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
- 思路
每个字符都有对应的ASCII,读入每个字符的时候,记录每个字符出现的编号,当不是第一次出现时,把此字符对应的编号设置为-1。这样就可以记录到只出现一次的字符并且包含字符出现的先后顺序。
最后把每个字符的编号遍历一次,找到编号最小的即为第一次出现的不重复字符。
参考于:https://www.nowcoder.com/profile/320158/codeBookDetail?submissionId=1500461
public class Solution {
int[] record = new int[256];
int cnt = 0;
//Insert one char from stringstream
public void Insert(char ch)
{
if(record[ch] == 0) {
record[ch] = ++cnt;
}else {
record[ch] = -1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char ch = '#';
int first = Integer.MAX_VALUE;
for(int i=0; i<256; i++) {
if(record[i] != 0 && record[i] != -1 && record[i] < first) {
first = record[i];
ch = (char)i;
}
}
return ch;
}
}