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
思路:
此题一看是双指针的题。首先思考什么时候移动左指针,什么时候移动右指针,每次移动需要记录点什么。
三个问题倒过来回答。
我用hash map来记录两个指针之间的元素及其个数。
当hash map的大小不超过k的时候,右指针向右移动一个单位。
当hash map的大小超过k的时候,左指针向右移动一个单位。
每当移动右指针,检查hash map的大小,更新最长子字符串长度。
每当移动左指针,检查hash map的大小。
什么是时候停止:
当右指针>=字符串长度时候。
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
hash = {}
left, right = 0, 0
longest = 0
while right < len(s):
if len(hash) <= k:
to_add = s[right]
if to_add in hash:
hash[to_add] += 1
else:
hash[to_add] = 1
if len(hash) <= k:
longest = max(longest, right-left+1)
right += 1
else:
to_sub = s[left]
left += 1
if hash[to_sub] > 1:
hash[to_sub] -= 1
else:
del hash[to_sub]
return longest
2021-08-04 圣荷西, ☀️, 太阳花快开完了。