Skip to content

Commit b868931

Browse files
committed
Refactor variable and add docstring
1 parent 7052b73 commit b868931

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

python/lengthOfLongestSubstring.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
11
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
22

3+
from typing import Set
4+
35

46
class Solution:
57
def lengthOfLongestSubstring(self, s: str) -> int:
6-
max_length = 0
7-
char_set = set()
8-
left = 0
9-
10-
# Iterate through the string
8+
"""
9+
Start by iterating through the entire string. We'll have a left
10+
and right pointer indicating a substring with the range
11+
[left, right]. If we encounter new characters, we increment right
12+
by one and update the maximum length as needed. If we encounter a
13+
duplicate, we increment left until that is no longer the case.
14+
"""
15+
max_length: int = 0
16+
char_seen: Set[str] = set()
17+
left: int = 0
1118
for right in range(len(s)):
12-
# We have a new unique character
13-
if s[right] not in char_set:
14-
char_set.add(s[right])
19+
if s[right] not in char_seen:
20+
char_seen.add(s[right])
1521
max_length = max(max_length, right - left + 1)
16-
17-
# We have an old character that came up again
1822
else:
19-
while s[right] in char_set:
20-
char_set.remove(s[left])
23+
while s[right] in char_seen:
24+
char_seen.remove(s[left])
2125
left += 1
22-
char_set.add(s[right])
23-
26+
char_seen.add(s[right])
2427
return max_length

0 commit comments

Comments
 (0)