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

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

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

import java.util.*;
public class Solution {
    LinkedList<Character> list = new LinkedList();
    Map<Character, Integer> map = new HashMap();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        // hashmap key char value count
        // !contains hashmap的 linkedlist add
        //     hashmap put 1
        // else hashmap get v+1
        if(map.containsKey(ch)) {
            map.put(ch,map.get(ch)+1);
        } else {
            list.add(ch);
            map.put(ch, 1);
        }
    }

    public char FirstAppearingOnce()
    {
        System.out.println(list.toString());
        // while peek is > 1
        while(!list.isEmpty() && map.get(list.peek()) > 1) {
            list.pop();
        }
        if(list.isEmpty()) {
            return '#';
        } else {
            return list.peek();
        }
    }
}

HashMap+LinkedList

map保存char和重复次数

list保存不重复的候选数字,因为可能第一个会因为出现重复被干掉,那么要马上能拿到下一个不重复的数字,所以最好是用list保存着。 这个解法比用StringBuilder要好一些,list中会把重复的pop出去。下次就不会加进来,get时候也不需要遍历到这种了。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 13:05
TMD找工作本来就烦,这东西什么素质啊😡
Beeee0927:hr是超雄了,不过也是有道理的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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