Given a string
s
and an integer k
, return the length of the longest substring of s
that contains at most k
distinct characters.Example 1:
Input: s = “eceba”, k = 2
Output: 3
Explanation: The substring is “ece” with length 3.
Example 2:
Input: s = “aa”, k = 1
Output: 2
Explanation: The substring is “aa” with length 2.
Constraints:
`1 <= s.length <= 5 104
*
0 <= k <= 50`题目大意:
求最长子串,它含有最多k种字符
解题思路:
同向双指针,属于最长串类型
解题步骤:
N/A
注意事项:
- while条件中,反计算char_to_count,还要pop key
Python代码:
1 | def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: |
算法分析:
时间复杂度为O(n)
,空间复杂度O(k)