zoukankan      html  css  js  c++  java
  • 剑指offer五十四之字符流中第一个不重复的字符

    一、题目

      请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"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

    ---------------------------------------------

    参考链接:

    https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  • 相关阅读:
    做项目时写的数据库操作类。SqlHelper.cs(三)
    写的登录三层结构demo(工厂模式)
    在GridView中进行排序
    微信小程序 POST请求
    mysql replace into用法详细说明
    ThinkPHP Where 条件中使用表达式
    Google发转码工具 可将安卓程序转至iOS
    IOS笔记 本地化多语言支持
    persits.jpeg 水印组件
    PHP 数组操作
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/7698667.html
Copyright © 2011-2022 走看看