395. Longest Substring with At Least K Repeating Characters
题目描述
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:s = "aaabb", k = 3
Output:3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:s = "ababbc", k = 2
Output:5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
分析
使用Counter函数对字符串中出现的每个字符进行计数,令出现次数小于k的字符作为字符串的分隔符,
join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
使用递归的方法:
(1)若字符串中的所有字符出现的次数均符合要求(>k),直接返回字符串的长度;
(2)若出现不符合要求的字符,递归统计以该字符为分隔符的其余子字符串的最长重复子串长度;
class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
for c in set(s): #set(s)将字符串转换成集合的形式
if s.count(c) < k: #若c的出现次数小于k,则直接切片
return max(self.longestSubstring(t,k) for t in s.split(c)) #将s用c切片
return len(s) #返回剩余字符串的长度