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

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

http://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720

队列:空间O(1),时间O(1)

import java.util.*;
public class Solution {
    //Map<Character,Integer> map = new LinkedHashMap<>();
    //Insert one char from stringstream
    int[] nums = new int[128];
    Queue<Character> queue = new LinkedList<>();
    public void Insert(char ch)
    {
        if(nums[ch]++ == 0){
            queue.add(ch);
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        while(!queue.isEmpty()){
            if(nums[queue.peek()]==1)
                return queue.peek();
            else queue.remove();
        }
        return '#';
    }
}

LinkedHashMap:空间O(N),时间O(1)

import java.util.*;
public class Solution {
    Map<Character,Integer> map = new LinkedHashMap<>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        if(map.containsKey(ch))
            map.put(ch,map.get(ch)+1);
        else
            map.put(ch,1);
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        for(char ch:map.keySet()){
            if(map.get(ch)==1)
                return ch;
        }
        return '#';
    }
}
全部评论

相关推荐

10-17 12:16
同济大学 Java
7182oat:快快放弃了然后发给我,然后让我也泡他七天最后再拒掉,狠狠羞辱他一把😋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务