Given A String, Find The Longest Substring With at Most 2 Different Characters
Given A String, Find The Longest Substring With at Most 2 Different Characters
G
Example:
“abcab” -> “ab”
"cacaaabbac" -> "cacaaa"
"ccaaabbac" -> "aaabba"
"aabbccbb" -> "bbccbb"
"ccaaabbacccccccccc” -> "acccccccccc"
To find the longest substring with at most 2 different characters in a given string, you can use a
python
Copy code
def
longest_substring_with_two_chars
(s):
if
not
s:
return
""
max_length =
0
start =
0
char_map = {}
for
end
in
range
(
len
(s)):
right_char = s[end]
char_map[right_char] = char_map.get(right_char,
0
)
+
1
while
len
(char_map) >
2:
left_char = s[start]
char_map[left_char] -=
1
if
char_map[left_char] ==
0
:
del
char_map[left_char]
start +=
1
max_length =
max
(max_length, end - start +
1
)
return
s[start:start + max_length]
# Example usage:
print
(longest_substring_with_two_chars(
"abcab"
)) #
Output: "ab"
print
(longest_substring_with_two_chars(
"cacaaabbac"
))
# Output: "cacaaa"
print
(longest_substring_with_two_chars(
"ccaaabbac"
))
# Output: "aaabba"
print
(longest_substring_with_two_chars(
"aabbccbb"
))
# Output: "bbccbb"
print
(longest_substring_with_two_chars(
"ccaaabbacccccccccc"
))
# Output: "acccccccccc"
This function maintains a sliding window represented by the variables
startand . It also keeps
end
expands until there are more than 2 distinct characters. When this happens, the window contracts
from the left side until there are only 2 distinct characters again, updating the
max_lengthalong the