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

[leetcode]Longest Substring with At Most Two Distinct Characters

时间:2014-11-26 16:10:45      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

很明显的2 pointer问题。。。当满足条件的时候后面的指针加,不满足条件的时候前面的指针加,直到满足条件。。。

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int start = 0, cnt = 0;
        int char_set[256] = {0};
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            if (char_set[s[i]]++ == 0) cnt++;
            while (cnt > 2) {
                char_set[s[start]]--;
                if (char_set[s[start++]] == 0) cnt--;
            }
            ans = max(i - start + 1, ans);
        }
        return ans;
    }
};

 

[leetcode]Longest Substring with At Most Two Distinct Characters

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/x1957/p/4123301.html

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