|
| 1 | +# Problem: Longest Substring Without Repeating Characters |
| 2 | +# Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ |
| 3 | +# Tags: String, Sliding Window, Hash Map |
| 4 | +# Approach: Use a sliding window with a dict mapping char -> last index. |
| 5 | +# Move 'right' over s; when a repeat is seen, jump 'left' to |
| 6 | +# max(left, last_index + 1). Track the maximum window length. |
| 7 | +# Time Complexity: O(n) |
| 8 | +# Space Complexity: O(k) where k is the charset size |
| 9 | + |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def lengthOfLongestSubstring(self, s): |
| 13 | + last = {} # char -> last index |
| 14 | + left = 0 |
| 15 | + max_len = 0 |
| 16 | + |
| 17 | + for right, ch in enumerate(s): |
| 18 | + if ch in last and last[ch] >= left: |
| 19 | + left = last[ch] + 1 # shrink window past the repeat |
| 20 | + last[ch] = right |
| 21 | + max_len = max(max_len, right - left + 1) |
| 22 | + |
| 23 | + return max_len |
0 commit comments