[LeetCode] Longest Substring with At Most Two Distinct Characters

Longest Substring with At Most Two Distinct Characters 

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.

滑动窗口。

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstringTwoDistinct(string s) {
 4         int res = 0, start = 0, end = 0;
 5         vector<int> mp(256, 0);
 6         int cnt = 0;
 7         for (end = 0; end < s.length(); ++end) {
 8             if (mp[s[end]] == 0) ++cnt;
 9             ++mp[s[end]];
10             if (cnt <= 2) res = max(res, end - start + 1);
11             while (cnt > 2) {
12                 --mp[s[start]];
13                 if (mp[s[start]] == 0) --cnt;
14                 ++start;
15             }
16         }
17         return res;
18     }
19 };

 

posted @ 2015-09-06 11:37  Eason Liu  阅读(193)  评论(0编辑  收藏  举报