描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
后台会用以下方式调用Insert 和 FirstAppearingOnce 函数
string caseout = "";
1.读入测试用例字符串casein
2.如果对应语言有Init()函数的话,执行Init() 函数
3.循环遍历字符串里的每一个字符ch {
Insert(ch);
caseout += FirstAppearingOnce()
}
2. 输出caseout,进行比较。
返回值描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
示例1
输入:
“google”
返回值:
“ggg#ll”
解题思路
通过队列记录字符串流,同时统计各个字符出现的次数,每次获取当前只出现一次的字符时,便去判断字符串出现的次数。
import java.util.Queue;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
public class Solution {
Queue<Character> queue=new LinkedList<>();
Map<Character,Integer> map=new HashMap<>();
//Insert one char from stringstream
public void Insert(char ch)
{
map.putIfAbsent(ch,0);
map.computeIfPresent(ch,(key,value)->value+1);
if(map.get(ch)<=1){
queue.offer(ch);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
while(!queue.isEmpty()){
Character ch=queue.peek();
int count=map.get(ch);
if(count>1){
queue.poll();
}
else{
return queue.peek();
}
}
return '#';
}
}