Length Of Longest Substring Two Distinct
Given a string S, find the length of the longest substring T that contains at most two distinct characters. For example, Given S = “eceba”, T is “ece” which its length is 3.
Solution: Count char occurances
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map
Solution: Save char index
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map
int lengthOfLongestSubstringTwoDistinct(string s) { int left = 0, right = -1, res = 0; for (int i = 1; i < s.size(); ++i) { if (s[i] == s[i - 1]) continue; if (right >= 0 && s[right] != s[i]) { res = max(res, i - left); left = right + 1; } right = i - 1; } return max(s.size() - left, res); }