Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 56ec01c

Browse files
Create longest_substring_without_repeating_characters.py
1 parent 4b278ac commit 56ec01c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /