zoukankan      html  css  js  c++  java
  • 剑指54.字符流中第一个不重复的字符

    题目描述

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

    输出描述:

    如果当前字符流没有存在出现一次的字符,返回#字符。
     

    思路

    思路1:使用HashMap+StringBuilder

    思路2:直接使用LinkedHashMap(有序的)。注意:LinkedHash的有序性是指插入的顺序,TreeMap的有序性是自动按值排序

    思路3:使用数组实现一个简单的Map

    解法1

    import java.util.*;
    public class Solution {
        private Map<Character,Integer> map = new HashMap<>();
        private StringBuilder sb = new StringBuilder();
        //Insert one char from stringstream
        public void Insert(char ch) {
            sb.append(ch);
            map.put(ch,map.getOrDefault(ch,0) + 1);
        }
        //return the first appearence once char in current stringstream
        public char FirstAppearingOnce() {
            int index = 0;
            while (index < sb.length()){
                if (map.get(sb.charAt(index)) == 1){
                    return sb.charAt(index);
                }
                index++;
            }
            return '#';
        }
    }

    解法2

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

    解法3

    Mark

     
     
  • 相关阅读:
    Integer的十进制转二,八,十六进制
    Java内存模型
    python gui --tkinter
    图论-最短路径
    Java NIO
    浏览器关闭后,Session就销毁了吗?
    mysql查询最新一条数据
    MySQL 查看命令执行时间
    MySQL 删除devices表中id最大的一行
    MySQL中的联表查询与子查询
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13611968.html
Copyright © 2011-2022 走看看