【leetcode】340 至多包含 K 个不同字符的最长子串(滑动窗口,双指针)

题目链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/

题目描述

给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T

示例 1:

输入: s = "eceba", k = 2
输出: 3
解释: 则 T 为 "ece",所以长度为 3。

示例 2:

输入: s = "aa", k = 1
输出: 2
解释: 则 T 为 "aa",所以长度为 2。

思路

/*
 * 滑动窗口+哈希表
 * 时间复杂度O(n) 空间复杂度O(k)
 */
class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        if(s.size() == 0 || k <= 0)
            return 0;
        unordered_map<char, int > m;
        int l = 0, r = 0;   // 滑动窗口左右指针
        int maxLen = 1;     // 最大长度
        int count = 0;
        while(r < s.size()){
            if (m[s[r]] == 0)
                count ++;
            m[s[r]] += 1;
            r++;
            // 左指针移动减小
            while (count > k){
                if(m[s[l]] == 1)
                    count--;
                m[s[l]] -= 1;
                l++;
            }
            maxLen = max(maxLen, r - l);
        }
        return maxLen;
    }
};

【leetcode】340 至多包含 K 个不同字符的最长子串(滑动窗口,双指针)_第1张图片

你可能感兴趣的:(【leetcode】340 至多包含 K 个不同字符的最长子串(滑动窗口,双指针))