字符流中第一個不重複的字符
描述
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"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:表示第一次出現的位置。