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 m; for (int i = 0; i < s.size(); ++i) { m[s[i]] += 1; while (m.size() > 2) { m[s[left]] -= 1; if (m[s[left]] == 0) m.erase(s[left]); left += 1; } res = max(res, i - left + 1); } return res; }

Solution: Save char index

int lengthOfLongestSubstringTwoDistinct(string s) { int res = 0, left = 0; unordered_map m; for (int i = 0; i < s.size(); ++i) { m[s[i]] = i; while (m.size() > 2) { if (m[s[left]] == left) m.erase(s[left]); ++left; } res = max(res, i - left + 1); } return res; }

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); }

results matching ""

    No results matching ""