[LeetCode] Longest Substring with At Most Two Distinct Characters

159. Longest Substring with At Most Two Distinct Characters

Given a string s, return the length of the longest substring that contains at most two distinct characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, counts[128]{0,};
for(int l = 0, r = 0, unique = 0; r < s.length(); r++) {
if(!counts[s[r]]) unique++;
counts[s[r]]++;
while(unique > 2) {
if(--counts[s[l]] == 0) unique--;
l++;
}
res = max(res, r - l + 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/longest-substring-with-at-most-two-distinct-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.