zoukankan      html  css  js  c++  java
  • 哈希表// 无重复字符的最长子串

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    示例 1:

    输入: "abcabcbb"
    输出: 3 
    解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
    

    示例 2:

    输入: "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
    

    示例 3:

    输入: "pwwkew"
    输出: 3
    解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
         请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int res = 0, left = 0, right = 0;
            HashSet<Character> t = new HashSet<Character>();
            while(right < s.length()){
                if(!t.contains(s.charAt(right))){
                    t.add(s.charAt(right));
                    right++;
                    res = Math.max(res, t.size());
                }else{
                    t.remove(s.charAt(left));
                    left++;
                }
            }
            return res;
        }
    }
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            HashMap<Character,Integer> hashMap = new HashMap<>();
            int res = 0, left = 0;
            for(int i = 0; i < s.length(); i++){
                if(hashMap.containsKey(s.charAt(i))){
                    left = Math.max(left, hashMap.get(s.charAt(i)));
                }
                res = Math.max(res,i-left+1);
                hashMap.put(s.charAt(i),i+1);
            }
            return res;
        }
    }
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] m = new int[256];
            int res = 0, left = 0;
            for(int i = 0; i < s.length(); i++){
                left = Math.max(left, m[s.charAt(i)]);
                res = Math.max(res, i-left+1);
                m[s.charAt(i)] = i+1;
            }
            return res;
        }
    }
  • 相关阅读:
    Aspose.word总结
    表格样式
    Aspose.Words 总结
    mysql主从复制
    WebApi系列~通过HttpClient来调用Web Api接口
    Memcached服务器安装、配置、使用详解
    Jqery之select操作
    Centos7 设置IPtables
    memcached全面剖析--5
    memcached全面剖析--4
  • 原文地址:https://www.cnblogs.com/strawqqhat/p/10602275.html
Copyright © 2011-2022 走看看