找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
示例 1:
输入:
s = "aaabb", k = 3
输出:
3
最长子串为 "aaa" ,其中 'a' 重复了 3 次。
示例 2:
输入:
s = "ababbc", k = 2
输出:
5
最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
【中等】
【分析】这道题的关键就是当字符x的次数小于k时,x字符串不能算在子字符串中,如此便在x左边和右边实施分治递归。
class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if len(s)==0:
return 0
for c in s:
if s.count(c)<k:
return max(longestSubstring(s0,k) for s0 in s.split(c))
return len(s)
#借鉴大佬的思想。。。
python中统计次数的一些函数:
#1
dic={};
for i in s:
dic[i]=dic.get(i,0)+1
#2
from collections import defaultdict
dic=defaultdict(int)
for i in s:
dic[i]+=1
#3: list和字符串都可以利用s.count(item)来返回s中item出现的次数
dic={}
for c in set(s):
dic[c]=s.count(c)
#4 counter函数,list和字符串都可以使用
from collections import Counter
dic=Counter(s)