首页 > 其他 > 详细

LeetCode "Longest Substring with At Most K Distinct Characters"

时间:2016-04-04 06:44:13      阅读:240      评论:0      收藏:0      [点我收藏+]

A simple variation to "Longest Substring with At Most Two Distinct Characters". A typical sliding window problem.

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        unordered_map<char, unsigned> hm;
        
        int ret = 0, start = 0;
        for (int i = 0; i < s.length(); i++)
        {
            hm[s[i]]++;

            if (hm.size() <= k)
            {
                ret = std::max(ret, i - start + 1);
            }
            else
            {
                while (start < i && hm.size() > k)
                {
                    char nc = s[start];
                    if (hm[nc] == 1)    hm.erase(nc);
                    else                hm[nc]--;
                    
                    start++;
                }
            }
        }
        return ret;
    }
};

LeetCode "Longest Substring with At Most K Distinct Characters"

原文:http://www.cnblogs.com/tonix/p/5351320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!