Skip to content

Commit 0a316b6

Browse files
committed
Longest Substring with At Most Two Distinct Characters
1 parent d402401 commit 0a316b6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
2+
#
3+
# Example 1:
4+
#
5+
# Input: "eceba"
6+
# Output: 3
7+
# Explanation: t is "ece" which its length is 3.
8+
# Example 2:
9+
#
10+
# Input: "ccaabbb"
11+
# Output: 5
12+
# Explanation: t is "aabbb" which its length is 5.
13+
14+
15+
class Solution:
16+
def lengthOfLongestSubstringTwoDistinct(self, s):
17+
last_char = ''
18+
second_last_char = ''
19+
last_char_count = 0
20+
maximum = 0
21+
currentMax = 0
22+
23+
for char in s:
24+
if char == last_char or char == second_last_char:
25+
currentMax += 1
26+
else:
27+
currentMax = last_char_count + 1
28+
29+
if char == last_char:
30+
last_char_count += 1
31+
else:
32+
last_char_count = 1
33+
second_last_char = last_char
34+
last_char = char
35+
36+
maximum = max(currentMax, maximum)
37+
38+
return maximum

0 commit comments

Comments
 (0)