|
2 | 2 |
|
3 | 3 |
|
4 | 4 | ```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. |
5 | 9 | fn len_longest_substr_no_char_repeats(s: StringLiteral) raises -> UInt16:
|
| 10 | + # If the input string is empty, return 0 immediately |
6 | 11 | if len(s) == 0:
|
7 | 12 | 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 |
8 | 16 | seen = Set(s[0])
|
| 17 | + |
| 18 | + # `left` is the left boundary of the current sliding window (start index) |
9 | 19 | left = 0
|
| 20 | + |
| 21 | + # Initial max_length is 1 since we already have one character in the set |
10 | 22 | max_length = 1
|
| 23 | + |
| 24 | + # Start iterating from the second character to the end of the string |
11 | 25 | 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 |
12 | 28 | while s[idx] in seen:
|
13 | 29 | seen.remove(s[left])
|
14 | 30 | left += 1
|
| 31 | + |
| 32 | + # Add the current character to the set |
15 | 33 | seen.add(s[idx])
|
| 34 | + |
| 35 | + # Update max_length with the size of the current window (set size) |
16 | 36 | max_length = max(max_length, len(seen))
|
| 37 | + |
| 38 | + # Return the maximum length found |
17 | 39 | return max_length
|
18 | 40 |
|
19 | 41 |
|
20 | 42 | fn main() raises:
|
21 | 43 | s = "abcabcbb"
|
22 |
| - print(len_longest_substr_no_char_repeats(s)) |
| 44 | + print(len_longest_substr_no_char_repeats(s)) # 3 |
23 | 45 | s = "bbbbb"
|
24 |
| - print(len_longest_substr_no_char_repeats(s)) |
| 46 | + print(len_longest_substr_no_char_repeats(s)) # 1 |
25 | 47 | s = "pwwkew"
|
26 |
| - print(len_longest_substr_no_char_repeats(s)) |
| 48 | + print(len_longest_substr_no_char_repeats(s)) # 3 |
| 49 | + |
27 | 50 | ```
|
28 | 51 |
|
29 | 52 |
|
|
0 commit comments