zoukankan      html  css  js  c++  java
  • LeetCode "Longest Substring with At Most K Distinct Characters"

    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;
        }
    };
  • 相关阅读:
    threading学习
    Python基础-5
    BS4
    requests基础
    Python基础-4
    Python基础-3
    Python基础-2
    Python基础-1
    DevOps
    nginx配置ssl证书实现https
  • 原文地址:https://www.cnblogs.com/tonix/p/5351320.html
Copyright © 2011-2022 走看看