-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_substring_without_repeating_characters.py
More file actions
80 lines (61 loc) · 2.19 KB
/
longest_substring_without_repeating_characters.py
File metadata and controls
80 lines (61 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
3. Longest Substring Without Repeating Characters
Time Complexity: O(n)
Space Complexity: O(min(n, m)) where m is charset size
"""
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
# Test cases
if __name__ == "__main__":
solution = Solution()
# Example 1
s1 = "abcabcbb"
print(f"Example 1: {solution.lengthOfLongestSubstring(s1)}") # Expected: 3
# "abc"
# Example 2
s2 = "bbbbb"
print(f"Example 2: {solution.lengthOfLongestSubstring(s2)}") # Expected: 1
# "b"
# Example 3
s3 = "pwwkew"
print(f"Example 3: {solution.lengthOfLongestSubstring(s3)}") # Expected: 3
# "wke"
# Edge case: empty string
s4 = ""
print(f"Example 4: {solution.lengthOfLongestSubstring(s4)}") # Expected: 0
# Edge case: single character
s5 = "a"
print(f"Example 5: {solution.lengthOfLongestSubstring(s5)}") # Expected: 1
# Edge case: all unique characters
s6 = "abcdef"
print(f"Example 6: {solution.lengthOfLongestSubstring(s6)}") # Expected: 6
# Edge case: with spaces and symbols
s7 = "a b c! @#"
print(f"Example 7: {solution.lengthOfLongestSubstring(s7)}") # Expected: 6
# " b c! @" or "b c! @#"
# Edge case: repeating at start
s8 = "aab"
print(f"Example 8: {solution.lengthOfLongestSubstring(s8)}") # Expected: 2
# "ab"
# Edge case: repeating at end
s9 = "abca"
print(f"Example 9: {solution.lengthOfLongestSubstring(s9)}") # Expected: 3
# "abc" or "bca"
# Edge case: long substring in middle
s11 = "aaabcdefgh"
print(f"Example 11: {solution.lengthOfLongestSubstring(s11)}") # Expected: 8
# "abcdefgh"
# Edge case: with digits
s12 = "123451234"
print(f"Example 12: {solution.lengthOfLongestSubstring(s12)}") # Expected: 5
# "12345"