剑指offer-64. 字符流中第一个只出现一次的字符-java

64. 字符流中第一个只出现一次的字符

双指针 队列 哈希表

原题链接

请实现一个函数用来找出字符流中第一个只出现一次的字符。

例如,当从字符流中只读出前两个字符 go 时,第一个只出现一次的字符是 g。

当从该字符流中读出前六个字符 google 时,第一个只出现一次的字符是 l。

如果当前字符流没有存在出现一次的字符,返回 # 字符。

数据范围
字符流读入字符数量 [0,1000]。

代码案例:输入:“google”
输出:“ggg#ll”
解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。

题解

题比较简单 看代码就可以

class Solution {    
    Set<Character> set = new LinkedHashSet<>();//这个是答案
    Set<Character> vis = new HashSet<>();
    //Insert one char from stringstream   
    public void insert(char ch){
        if(set.contains(ch))
            set.remove(ch);
        if(!vis.contains(ch)) {
            set.add(ch);
            vis.add(ch);            
        }
    }
    //return the first appearence once char in current stringstream
    public char firstAppearingOnce(){
        for(char ch : set)
            return ch;
        return '#';
    }

 
}

posted @ 2022-10-11 20:07  依嘫  阅读(28)  评论(0)    收藏  举报