Skip to content

[LeetCode 3] 无重复字符的最长子串

中等已解决Aug 13, 2025(152天前) 时间 O(n) 空间 O(1) 原题链接

🎯 请点击上方原题链接,查看题目描述👆

💭 解题思路#

  1. 定义一个“窗口”,“窗口”的左边界 left = 0 ,右边界 right = 0
  2. 定义一个 Map 字典,字典里的 key 记录着窗口增大时途径的节点。 value 为节点 key 的下标值,每次窗口右边界增大 right++ ,就检查右边界下标 right 对应的字符在不在“字典”:

理解左窗口缩小的时机是需要我们解题的关键!

假设当前窗口右边界 right 对应的字符为 A,上一次字符A出现的下标为 indexleft < index < right 是不是就说明了出现重复字符了,只有这时候才需要缩小窗口

💻 代码实现#

class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> window = new HashMap<>();
int left = 0,right = 0,res = 0;
while(right < s.length()){
char temp = s.charAt(right);
if(window.containsKey(temp)){
res = Math.max(res,(right - left));
//这里是关键,很多人都写成了 left = window.get(temp) + 1;
left = Math.max(left,window.get(temp) + 1);
}
window.put(temp,right);
right++;
}
res = Math.max(res,(right - left));
return res;
}
}