Skip to content

Commit 6571c6e

Browse files
committed
Create longest-substring-with-at-most-two-distinct-characters.cpp
1 parent 52e1760 commit 6571c6e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int lengthOfLongestSubstringTwoDistinct(string s) {
7+
const int k = 2;
8+
int longest = 0, start = 0, distinct_count = 0;
9+
array<int, 256> visited = {0};
10+
for (int i = 0; i < s.length(); ++i) {
11+
if (visited[s[i]] == 0) {
12+
++distinct_count;
13+
}
14+
++visited[s[i]];
15+
while (distinct_count > k) {
16+
--visited[s[start]];
17+
if (visited[s[start]] == 0) {
18+
--distinct_count;
19+
}
20+
++start;
21+
}
22+
longest = max(longest, i - start + 1);
23+
}
24+
return longest;
25+
}
26+
};

0 commit comments

Comments
 (0)