題目描述
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。如果當前字符流沒有存在出現一次的字符,返回#字符。
解法
哈希表解決
import java.util.*;
public class Solution {
private Hashtable<Character,Boolean> ht = new Hashtable<Character,Boolean>();
private ArrayList<Character> al = new ArrayList<Character>();
//Insert one char from stringstream
public void Insert(char ch)
{
if(ht.containsKey(ch)){
ht.put(ch,false);
}
else{
ht.put(ch,true);
}
al.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(char c:al){
if(ht.get(c)){
return c;
}
}
return '#';
}
}