标签:ret etc word div value maxsize break 算法 bre
1 class Solution: 2 def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: 3 n = len(s) 4 if n < minSize: 5 return 0 6 left,right = 0,0 7 #dic = {} 8 res = {} 9 while left <= n - minSize: 10 for width in range(minSize,maxSize+1): 11 right = left + width 12 if right > n: 13 break 14 #print(‘width:‘,width,‘left:‘,left,‘right:‘,right) 15 dic = {} 16 diffcount = 0 17 for i in range(left,right): 18 cur = s[i] 19 if cur not in dic: 20 dic[cur] = 1 21 diffcount += 1 22 else: 23 dic[cur] += 1 24 if diffcount <= maxLetters: 25 word = s[left:right] 26 if word not in res: 27 res[word] = 1 28 else: 29 res[word] += 1 30 else: 31 break 32 left += 1 33 if len(res) > 0: 34 return max(res.values()) 35 else: 36 return 0
算法思路:滑动窗口。
窗口的范围是[minSize,maxSize]之间,left从左到右遍历,每次得到一个right。
统计left到right这个窗口内的元素,有多少个不同元素,是否满足maxLetters限制。
如果满足条件则存储进res中,最后返回res出现次数最多的值(value)。
标签:ret etc word div value maxsize break 算法 bre
原文地址:https://www.cnblogs.com/asenyang/p/12079598.html