字符流中第一个不重复的字符
描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。如果当前字符流没有存在出现一次的字符,返回#字符。
代码 (Java)
import java.util.Arrays;
public class Solution {
// 记录字符的位置,-1:没出现过,-2:出现多次,>=0:表示第一次出现的位置
int[] location = new int[256];
int index = 0;
public void Insert(char ch) {
if (index == 0)
Arrays.fill(location, -1);
if (location[(int)ch] == -1)
location[(int)ch] = index;
else if (location[(int)ch] >= 0)
location[(int)ch] = -2;
index++;
}
public char FirstAppearingOnce() {
if (index == 0)
Arrays.fill(location, -1);
char result = '#';
int minIndex = Integer.MAX_VALUE;
for (int i = 0; i < 256; ++i) {
if (location[i] >= 0 && location[i] < minIndex) {
result = (char)i;
minIndex = location[i];
}
}
return result;
}
}
思路
- 这题跟 第一个只出现一次的字符 很像,只不过这道题是字符流(很长或者无法每次遍历,只能一次读取一个),这道题的解法也适用那题。
- 同样也用到空间换时间的思想,用哈希表 location 来记录字符出现的位置,-1:没出现过,-2:出现多次,>=0:表示第一次出现的位置。