首页 > 其他 > 详细

[LeetCode] Longest Substring with At Most Two Distinct Characters

时间:2015-09-06 12:36:34      阅读:165      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!