Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”,
T is "ece" which its length is 3.
Hide Company Tags Google
Hide Tags Hash Table Two Pointers String
Hide Similar Problems (M) Longest Substring Without Repeating Characters (H) Sliding Window Maximum
记得看到一个blog说:这种题,一般都在于用一个hash table 和两个reference。 不同之处在于如何update start point.
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
if(s.empty()) return 0;
int dict[256] = {0};
int cnt = 0, start = 0, maxLen = 1;
for (int i = 0; i<s.size(); ++i) {
++dict[s[i]];
if (dict[s[i]] == 1) { // new char
++cnt;
while (cnt > 2) {
--dict[s[start]];
if(!dict[s[start]]) --cnt; // mp[s[i] indicates: from start to current position, how many s[i] the substr has. if(!mp[s[start]]) then s[start] no longer exist we can --cnt;
++start;
}
}
maxLen = max(maxLen, i-start + 1);
}
return maxLen;
}
};