java - 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。
解决方案
[a,b,c,a] 的迭代
- 设置 {a}, l=0, r=1 , max = 1
- 设置 {a, b}, l=0, r=2 , max = 2
- 设置 {a,b,c}, l=0, r=3, max =3
- 设置 {b,c}, l=1, r=3, max= 3
- 设置 {b,c,a}, l=1, r=4, max=3
这应该有助于了解该算法的工作原理。
推荐阅读
- python - 有没有办法用 Keras ImageDataGenerator 和 Tensorflow 制作更小的时代?
- mysql - MySQL sum() 按月和年的值每次都会给我不同的结果
- algorithm - 双积分的自适应辛普森求积算法?
- apache - 重写每个 php 文件的异常
- loops - 为什么这个循环不起作用?它只改变 a 的值,但从不改变 b、c 或 d 的值
- javascript - 当我稍后在脚本中尝试打印用户输入的单词时,为什么它会在我的网站上显示“null”?
- sql - 比较列日期/w 今天日期
- encryption - 如何使用非对称密钥对加密和使用对称密钥
- r - 按变量级别连接点
- docker - Docker 和 Letsencrypt 证书的 Keycloak 错误