Skip to content

Commit a4072ed

Browse files
committed
2 parents 40e39aa + d02bd7c commit a4072ed

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

docs/longest_substr_no_char_repeats.md

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,51 @@
22

33

44
```python
5+
from collections import Set
6+
7+
# Function to compute the length of the longest substring without repeating characters.
8+
# Takes a StringLiteral `s` and returns an unsigned 16-bit integer.
59
fn len_longest_substr_no_char_repeats(s: StringLiteral) raises -> UInt16:
10+
# If the input string is empty, return 0 immediately
611
if len(s) == 0:
712
return 0
13+
14+
# Initialize a Set to keep track of characters in the current window (substring)
15+
# Start by adding the first character of the string
816
seen = Set(s[0])
17+
18+
# `left` is the left boundary of the current sliding window (start index)
919
left = 0
20+
21+
# Initial max_length is 1 since we already have one character in the set
1022
max_length = 1
23+
24+
# Start iterating from the second character to the end of the string
1125
for idx in range(1, len(s)):
26+
# If the current character is already in the set, it means a repetition
27+
# So we move the `left` boundary forward until we remove the duplicate
1228
while s[idx] in seen:
1329
seen.remove(s[left])
1430
left += 1
31+
32+
# Add the current character to the set
1533
seen.add(s[idx])
34+
35+
# Update max_length with the size of the current window (set size)
1636
max_length = max(max_length, len(seen))
37+
38+
# Return the maximum length found
1739
return max_length
1840

1941

2042
fn main() raises:
2143
s = "abcabcbb"
22-
print(len_longest_substr_no_char_repeats(s))
44+
print(len_longest_substr_no_char_repeats(s)) # 3
2345
s = "bbbbb"
24-
print(len_longest_substr_no_char_repeats(s))
46+
print(len_longest_substr_no_char_repeats(s)) # 1
2547
s = "pwwkew"
26-
print(len_longest_substr_no_char_repeats(s))
48+
print(len_longest_substr_no_char_repeats(s)) # 3
49+
2750
```
2851

2952

0 commit comments

Comments
 (0)