Longest Substring Without Repeating Characters 解題教學:3 種解法完整比較|LeetCode 3 Best Practice

Longest Substring Without Repeating Characters 解題教學封面|LeetCode 3
Longest Substring Without Repeating Characters|LeetCode 3 解題重點整理
Longest Substring Without Repeating Characters|LeetCode 3 解題重點整理

本文完整拆解 LeetCode 3 Longest Substring Without Repeating Characters 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Longest Substring Without Repeating Characters 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given a string s, find the length of the longest substring without repeating characters.

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Python

				
					# time complexity: O(n)
# space complexity: O(min(m,n))
from collections import Counter


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        chars = Counter()
        left = right = 0
        res = 0
        while right < len(s):
            r = s[right]
            chars[r] += 1
            while chars[r] > 1:
                l = s[left]
                chars[l] -= 1
                left += 1
            res = max(res, right - left + 1)
            right += 1
        return res


Input = "abcabcbb"
print(Solution().lengthOfLongestSubstring(Input))
				
			

Longest Substring Without Repeating Characters 解題思路

要找沒有重複字元的最長子字串,暴力列舉所有子字串是 O(n²) 起跳。滑動視窗的關鍵觀察是:當右端遇到重複字元時,左端不必退回去一格一格試,而是可以直接跳到「上一次出現該字元的下一格」,因為中間任何起點都還是會撞到同一個重複。

Longest Substring Without Repeating Characters 演算法步驟

  1. 用雜湊表記錄每個字元最後出現的索引,left 指向目前視窗左界。
  2. 右指針 right 由左往右掃描每個字元 ch。
  3. 若 ch 出現過且上次索引大於等於 left,就把 left 跳到「上次索引 + 1」。
  4. 更新 ch 的最後索引,並用 right – left + 1 更新答案的最大值。

Longest Substring Without Repeating Characters 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(min(n,m))

右指針走訪 n 次,左指針只會單調往右移動,總移動量也是 O(n),所以時間是 O(n)。雜湊表最多存下字元集合大小 m 或字串長度 n 的較小值,空間為 O(min(n,m))。

Longest Substring Without Repeating Characters 的邊界情況與常見錯誤

  • 空字串答案為 0。
  • left 的跳躍一定要取 max(left, 上次索引 + 1),否則舊的重複會把 left 往回拉。
  • 字串可能包含空白、數字與符號,不要假設只有英文字母。
  • 答案是長度而不是子字串本身,若要回傳內容需額外記錄起點。

Longest Substring Without Repeating Characters 其他解法比較

解法時間空間說明
列舉所有子字串並檢查O(n³)O(min(n,m))最直覺但完全無法過大測資
滑動視窗逐格收縮左界O(n)O(min(n,m))正確但左界移動較瑣碎
滑動視窗 + 最後索引跳躍O(n)O(min(n,m))本文採用,左界一次到位