码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Longest Substring with At Most Two Distinct Characters

时间:2015-09-06 12:38:14      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode] Longest Substring with At Most Two Distinct Characters

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4785057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!