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

     
     
  • 相关阅读:
    OAuth 2.0 访问新浪、腾讯的资源服务器
    OAuth 2.0 Authorization Code授权方式详解
    linux权限补充:rwt rwT rws rwS 特殊权限
    异步服务器框架设计
    vsftpd常规操作指南
    folly学习心得
    中国人口趋势(19902035)
    hbase系统搭建
    过载保护
    穷人和富人
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13611968.html
Copyright © 2011-2022 走看看