NeetCode #230LC-3MediumSliding WindowBlind 75NC 150NC 250
← Back to All Problems#230 · #3 · Longest Substring Without Repeating Characters(无重复字符的最长子串)
📌 Problem Statement & Constraints
Given a string
s, find the length of the longest substring without repeating characters. Constraints: 0 <= s.length <= 5 * 10^4; s consists of ASCII characters.💡 Core Algorithmic Approaches
- Maintain a window
[l, r]containing no duplicate characters, and a map from character to its last seen index. - When
s[r]was last seen at indexp >= l, the window must jump:l = p + 1. - The window length is then
r - l + 1, and the answer is its maximum. - Using the last-seen index (rather than a set with a shrink loop) makes the left pointer jump directly, which is both simpler and faster.
💻 Benchmark Python3 Implementation
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last = {} # character -> last seen index
l = 0
best = 0
for r, ch in enumerate(s):
if ch in last and last[ch] >= l:
l = last[ch] + 1 # jump past the previous occurrence
last[ch] = r
best = max(best, r - l + 1)
return best
# Set-based variant with an explicit shrink loop
class Solution2:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = set()
l = 0
best = 0
for r, ch in enumerate(s):
while ch in seen: # shrink until the duplicate is gone
seen.remove(s[l])
l += 1
seen.add(ch)
best = max(best, r - l + 1)
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each character enters and leaves the window at most once.
💾 Space Complexity
O(k) where k is the size of the character set (at most 128 for ASCII).
⚠️ Interview Pitfalls & Follow-ups
- Using
l = last[ch] + 1without thelast[ch] >= lguard: the left pointer could move backwards, which is wrong. The guard is essential. - Comparing
last[ch]with 0 instead ofl: the relevant question is whether the previous occurrence is inside the current window. - Resetting the whole window on a duplicate: that would miss longer windows that start after the first occurrence of the duplicate.
- Returning the window's length instead of the maximum: the window shrinks over time, so the maximum must be tracked.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
无重复字符的最长子串
给定一个字符串 s,请你找出其中不含有重复字符的 最长子串 的长度。约束:0 ≤ s.length ≤ 5 × 10^4;s 由英文字母、数字、符号和空格组成。
核心要点
- 滑动窗口 + 字符最后位置表(标准解) :维护窗口左边界 l 与一个字典 last (字符 → 最近出现的下标)。
- 扩展右边界 :遍历 r,若 s[r] 上次出现的位置 last[s[r]] 在窗口内(即 >= l ),则把 l 跳到 last[s[r]] + 1 ,保证窗口内无重复。
- 为什么可以直接跳跃 :若 s[r] 与窗口内位置 p 重复,则任何包含 p 的窗口都会与 r 冲突,因此 l 必须至少为 p + 1 。
- 记录答案 :每步用窗口长度 r − l + 1 更新答案。
常见陷阱
- 忘记判断 last[c] >= l :若上次出现的位置已在窗口 左侧之外 ,则不影响当前窗口,此时不应移动 l。漏掉这个判断会把 l 错误地往回跳,导致答案偏小。
- 用 while s[r] in window: remove(s[l]); l += 1 逐个收缩 :正确但常数更大;直接用「最后位置表 + 跳跃」是 O(n) 的更优写法。
- 用集合判断重复后逐个删除 :集合无法记录位置,必须逐个收缩窗口,效率低于位置表法。
- 空字符串 :应返回 0,本解天然正确。
参考实现
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last = {} # 字符 -> 最近出现的下标
l = 0 # 窗口左边界
best = 0
for r, c in enumerate(s):
if c in last and last[c] >= l:
l = last[c] + 1 # 直接跳到重复字符之后,无需逐个收缩
last[c] = r
if r - l + 1 > best:
best = r - l + 1
return best