題目描述
請實現(xiàn)一個函數(shù)用來找出字符流中第一個只出現(xiàn)一次的字符。例如民宿,當(dāng)從字符流中只讀出前兩個字符"go"時往枣,第一個只出現(xiàn)一次的字符是"g"。當(dāng)從該字符流中讀出前六個字符“google"時用爪,第一個只出現(xiàn)一次的字符是"l"原押。
題解
和上一題一樣,一樣可以使用哈希表來保存每個字符出現(xiàn)的次數(shù)偎血,但由于HashMap是無序的诸衔,無法記錄輸入字符流的順序,因此使用LinkedHashMap颇玷。
時間復(fù)雜度為O(n)笨农,空間復(fù)雜度為O(1)。
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
public void Insert(char ch)
{
if (!map.containsKey(ch))
map.put(ch, 1);
else map.put(ch, map.get(ch)+1);
}
public char FirstAppearingOnce()
{
for (char ch : map.keySet()) {
if (map.get(ch) == 1)
return ch;
}
return '#';
}