版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40244153/article/details/87466208
题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:如果当前字符流没有存在出现一次的字符,返回#字符。
两个辅助空间
(1)HashMap 根据字符放入map中每次将次数加1;
(2)ArrayList 将插入的每个字符放入到list中,list是有顺序地存放。遍历list去map中根据字符找其出现的次数。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Solution {
Map<Character,Integer> map = new HashMap<>();
ArrayList<Character> list = new ArrayList<Character>();//存放字符
//Insert one char from stringstream
public void Insert(char ch)
{
if(map.containsKey(ch)){
map.replace(ch,map.get(ch)+1);
}else{
map.put(ch,1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(int i = 0; i < list.size(); i++)
{
if(map.get(list.get(i)) == 1)
{
return list.get(i);
}
}
return '#';
}
}
知识点:map无序,list有序 map的put方法可以覆盖