Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2016-04-04 02:53  Tonix  阅读(193)  评论(0编辑  收藏  举报