題目描述
- 請實現(xiàn)一個函數(shù)用來找出字符流中第一個只出現(xiàn)一次的字符袱耽。例如死遭,當(dāng)從字符流中只讀出前兩個字符"go"時鞠眉,第一個只出現(xiàn)一次的字符是"g"。當(dāng)從該字符流中讀出前六個字符“google"時嫉沽,第一個只出現(xiàn)一次的字符是"l"辟犀。
輸出描述
- 如果當(dāng)前字符流沒有存在出現(xiàn)一次的字符,返回#字符绸硕。
解題思路
- 采用散列表存儲堂竟,鍵存儲的是字符,值存儲的是字符的次數(shù)
- 因為是數(shù)據(jù)流讀入要保證數(shù)據(jù)的順序性玻佩,因此我采用LinkedHashMap實現(xiàn)出嘹,HashMap是無序的,但LinkedHashMap是有序表咬崔,因此可以滿足要求
- 靜態(tài)代碼塊用于初始化map
- 插入的過程就是檢索是否存在這個key税稼,存在就將值加1烦秩,不存在就將put值1進(jìn)去
- 取出的過程就是從頭遍歷,然后找到第一個value值是1的將其返回
Java源代碼
import java.util.*;
public class Solution {
private static Map<Character, Integer> map;
{
map = new LinkedHashMap<>();
}
//Insert one char from stringstream
public void Insert(char ch)
{
if (map.containsKey(ch)) {
int temp = map.get(ch);
map.put(ch, temp+1);
}
else map.put(ch, 1);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue()==1) return entry.getKey();
}
return '#';
}
}