题解 | #字符流中第一个不重复的字符#

字符流中第一个不重复的字符

https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720

import java.util.*;
public class Solution {
    public Map<Character,Integer> myMap=new HashMap<>();
    Queue<Character> queue=new LinkedList<>();


    //Insert one char from stringstream
    public void Insert(char ch)
    {
        myMap.put(ch,myMap.getOrDefault(ch,0)+1);
        queue.offer(ch);
        //清理队列头部不再是第一个不重复的字符的元素   可能有多个重复元素
        while(!queue.isEmpty()&&myMap.get(queue.peek())>1){
            queue.poll();
        }

        
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        if(queue.isEmpty()){
            return '#';
        }
        return queue.peek(); // 队列头部的字符是第一个不重复的字符
        
    }
}

全部评论

相关推荐

想进开水团喝开水:哦 给我一个 就算你真拿到牛友也会为你开心的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务