题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
题解:insert()函数中使用ArrayList来保存字符,同时使用HashMap保存字符出现的次数,在FirstAppearingOnce()中遍历list获取到map中第一次在字符流中只出现一次的字符。
import java.util.ArrayList;
import java.util.HashMap;
public class Solution {
ArrayList<Character> list = new ArrayList<>();
HashMap<Character, Integer> map = new HashMap<>();
public void Insert(char ch)
{
list.add(ch);
if(!map.containsKey(ch)){
map.put(ch, 1);
}else {
map.put(ch,map.get(ch)+1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char ch = '#';
for(int i=0;i<list.size();i++){
if(map.get(list.get(i))==1){
ch = list.get(i);
break;
}
}
return ch;
}
}