题干
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
思路
个人觉得和判断数组中第一个只出现一次的数字有异曲同工之秒,只不过这个是一个一个读入的,不需要循环判断。
代码
import java.util.HashMap;
import java.util.ArrayList;
public class Solution {
//Insert one char from stringstream
HashMap <Character,Integer> hash=new HashMap<Character,Integer>();
ArrayList <Character>list=new ArrayList<>();
public void Insert(char ch)
{
if(hash.containsKey(ch)){
Integer value=hash.get(ch);
hash.remove(ch);
hash.put(ch,value+1);
}
else
hash.put(ch,1);
list.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(int i=0;i<list.size();i++)
if(hash.get(list.get(i))==1)
return list.get(i);
return '#';
}
}