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

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int n = s.length(), ans = 0;
            Map<Character, Integer> map = new HashMap<>(); // current index of character
            // try to extend the range [i, j]
            for (int j = 0, i = 0; j < n; j++) {
                if (map.containsKey(s.charAt(j))) {
                    i = Math.max(map.get(s.charAt(j)), i); //max的作用是保证i不会突然变小, 例如abbba, 到最后一个a的时候如果没有max,这个i会突然变小导致算错
                }
                ans = Math.max(ans, j - i + 1); j表示当前索引 , i是最左边的位置, 当前范围是从i到j 全包含, 所以+1
                map.put(s.charAt(j), j + 1);  更新字符索引,这里的+1意思是存该字符靠右一个位置;因为必须考虑初始情况,
            }
            return ans;
        }
    }
    

      

  • 相关阅读:
    双循环解决添加列表问题
    贪心算法
    隔板法发红包
    python小兵之时间模块
    开发规范
    python 小兵(12)模块1
    Linux系统
    刷题
    Socket
    栈和队列
  • 原文地址:https://www.cnblogs.com/lychnis/p/10604167.html
Copyright © 2011-2022 走看看