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

LeetCode "Longest Substring with At Most Two Distinct Characters"

时间:2015-08-21 15:08:55      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

A typical sliding window solution.

技术分享
class Solution {
    int rec[26];    // for a-z
    int rec1[26];    // for A-Z
    int cnt;
    int &getCnt(char c)
    {
        if (c >= a && c <= z)
            return rec[c - a];
        if (c >= A && c <= Z)
            return rec1[c - A];
    }
public:
    int lengthOfLongestSubstringTwoDistinct(string s) 
    {
        std::fill(rec, rec + 26, 0);
        std::fill(rec1, rec1 + 26, 0);
        cnt = 0;

        int ret = 0;
        int start = 0;
        for (int i = 0; i < s.length(); i++)
        {
            char c = s[i];
            if (getCnt(c) == 0) cnt++;
            getCnt(c)++;

            int len = i - start + 1;
            if (cnt <= 2)
            {
                ret = std::max(ret, len);
            }
            else
            {
                while (start < i && cnt > 2)
                {
                    char nc = s[start];
                    if (getCnt(nc) == 1)
                        cnt--;
                    
                    getCnt(nc)--;
                    start++;
                }
            }
        }
        return ret;
    }
};
View Code

LeetCode "Longest Substring with At Most Two Distinct Characters"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4747604.html

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