240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 21 | Leetcode 340. Longest Substring with At Most K Distinct Characters

题解

Hard

Sliding Window

事实证明,掌握套路还是很有用的。用 sliding window 模板套路解决这道题还是比较顺利的,虽然是一道 Hard 级别的题。当然,有一点冗余,可以精简一下。

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        int max_start = 0, max_len = 0;
        int start = 0, end = 0;
        
        unordered_map<char, int> m;
        
        while(end < s.size()) {
            m[s[end]]++;
            
            while(m.size() > k) {
                m[s[start]]--;
                if(m[s[start]] == 0) m.erase(s[start]);
                start++;
            }
            
            if(m.size() <= k) {
                int len = end-start+1;
                if(len > max_len) {
                    max_len = len;
                    max_start = start;
                }
            }
            
            end++;
        }
        
        return max_len;
    }
};

精简后。

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        int max_len = 0;
        int start = 0, end = 0;
        
        unordered_map<char, int> m;
        
        while(end < s.size()) {
            m[s[end]]++;
            
            while(m.size() > k) {
                m[s[start]]--;
                if(m[s[start]] == 0) m.erase(s[start]);
                start++;
            }
            
            if(m.size() <= k) {
                max_len = max(max_len, end-start+1);
            }
            
            end++;
        }
        
        return max_len;
    }
};
posted @ 2020-10-09 14:22  CasperWin  阅读(108)  评论(0编辑  收藏  举报