0%

159. Longest Substring with At Most Two Distinct Characters

O(n) time O(26) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
unordered_map<char, int> m;
int n = s.length();
int res = 0;
for (int l = 0, r = 0; r < n; ++r) {
++m[s[r]];
while (l < r && m.size() > 2) {
if (--m[s[l]] == 0) {
m.erase(s[l]);
}
++l;
}
res = max(res, r + 1 - l);
}
return res;
}
};

lee的做法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
unordered_map<char, int> m;
int n = s.length();
int res = 0, l = 0, r = 0;
for (; r < n; ++r) {
++m[s[r]];
if (m.size() > 2) {
if (--m[s[l]] == 0) {
m.erase(s[l]);
}
++l;
}
}
return r - l;
}
};