zoukankan      html  css  js  c++  java
  • LeetCode 3. Longest Substring Without Repeating Characters

    3. Longest Substring Without Repeating Characters(无重复字符的最长子串)

    链接

    https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

    题目

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

    示例 1:

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

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

    输入: "pwwkew"
    输出: 3
    解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
      请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

    思路

    滑动窗口的题目,做出来不是很难,但是要优化就很麻烦。
    这里设置了两个指针,同时借助了hashmap来去重。循环比较每一个字符,如果字符不存在就加入,如果存在了,就看在left左还是右,左侧无需在意,右侧更新,最后输出max即可。
    (这里没有和left比较,而是直接取了较大值,left就代表当前字符串左侧,right代表当前字符串右侧)

    代码

      public static int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if (len == 0) {
          return 0;
        }
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        int left = 0;
        for (int right = 0; right < len; right++) {
          if (map.containsKey(s.charAt(right))) {
            left = Math.max(left, map.get(s.charAt(right)) + 1);
          }
          map.put(s.charAt(right), right);
          max = Math.max(max, right - left + 1);
        }
        return max;
      }
    
  • 相关阅读:
    matplotlib种类
    matplotlib安装
    Python input保证输入为int类型
    centos7 安装 smplayer
    matplotlib与numpy
    Windows系统pip安装whl包
    python3打开winodows文件问题
    centos7 python3 pip
    Python实战171203统计
    Python实战171202元组访问
  • 原文地址:https://www.cnblogs.com/blogxjc/p/12323533.html
Copyright © 2011-2022 走看看