Leetcode 340. 至多包含 K 个不同字符的最长子串 典型的滑动窗口双指针技巧

典型的滑动窗口双指针技巧

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        int n = s.size(), res = 0;
        unordered_map<char,int> hashmap;
        for(int i=0,j=0;j<n;j++){
            hashmap[s[j]]++;
            while(i<n&&hashmap.size()>k){
                hashmap[s[i]]--;
                if(hashmap.count(s[i])&&hashmap[s[i]]==0) hashmap.erase(s[i]);
                i++;
            }
            res = max(res,j-i+1);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108367594