首页 > 解决方案 > Leetcode Q3 - 为什么返回 and 而不是 (ans+1)?

问题描述

Leetcode 链接: https ://leetcode.com/problems/longest-substring-without-repeating-characters/

以下是我使用 set 的代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] arr = s.toCharArray();
        int n = s.length();
        int left = 0, right = 0, ans = 0;
        Set<Character> set = new HashSet<>(); 
        if (s == null || s.length() == 0) return ans;
        
        while (left < n && right < n) {
            if (!set.contains(arr[right])) set.add(arr[right++]);
            else {
                while (set.contains(arr[right])) {
                    set.remove(arr[left++]);
                }
            }
            ans = Math.max(ans, right - left);
        }
        return ans;
    }
}

我的理解,比如,[a,b,c,a]right = 3,,,left = 0然后set remove 'a'(其索引为0) ,,,,,,,,left++那么left = 1,应该返回(3-1)+1。

标签: java

解决方案


[a,b,c,a] 的迭代

  1. 设置 {a}, l=0, r=1 , max = 1
  2. 设置 {a, b}, l=0, r=2 , max = 2
  3. 设置 {a,b,c}, l=0, r=3, max =3
  4. 设置 {b,c}, l=1, r=3, max= 3
  5. 设置 {b,c,a}, l=1, r=4, max=3

这应该有助于了解该算法的工作原理。


推荐阅读