一、题目

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

二、思路

     使用LinkedHadshMap统计字符个数,详见代码注释

三、代码

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class Solution {
    LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        //统计字符的个数,注意用LinkedHashMap
            if (lhm.containsKey(ch)) {
                lhm.put(ch, lhm.get(ch) + 1);
            } else {
                lhm.put(ch, 1);
            }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        //遍历map,寻找第一个只出现一次的数
        char num = 0;
        int flag=0; //判断有没有只出现一次的字符
        Set<Map.Entry<Character, Integer>> set = lhm.entrySet();
        for (Map.Entry<Character, Integer> es : set) {
            char key = es.getKey();
            int value = es.getValue();
            if (value == 1) {
                num = key;
                flag=1;//有只出现一次的字符
                break;
            }
        }
        //没有只出现一次的字符,返回‘#’
        if(flag==0){
            num='#';
        }
        flag=0;//复位,为下一次判断准备
        return num;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-06-20
  • 2022-01-02
  • 2021-10-04
  • 2022-02-19
  • 2022-12-23
  • 2022-01-16
  • 2022-01-06
猜你喜欢
  • 2021-11-26
  • 2021-09-18
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2021-12-01
相关资源
相似解决方案