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

LeetCode "Longest Substring with At Most K Distinct Characters"

时间:2016-04-04 06:44:56      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!