56.字符流中第一个不重复的数

题目描述:

  请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

思路分析:

  由于是字符流所以我们需要设置一个空字符串,每次进来一个字符我们就将其加入字符串,同时设置一个map,记录字符和其出现的次数。这样在判断的时候我们可以遍历现有的字符串,找出第一个出现次数为1的字符。

代码:

import java.util.*;
public class Solution {
    //Insert one char from stringstream
    HashMap<Character,Integer>map=new HashMap<>();
    String s="";
    public void Insert(char ch)
    {
        s=s+ch;
        if(map.containsKey(ch)){
            int count=map.get(ch);
            count++;
            map.put(ch,count);
        }else{
            map.put(ch,1);
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        for(int i=0;i<s.length();i++){
            if(map.get(s.charAt(i))==1){
                  return s.charAt(i);
     }
            }
        return '#';
    }
}

猜你喜欢

转载自www.cnblogs.com/yjxyy/p/10947087.html
今日推荐