lc 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.
题目要求最长,若不是因为部分字母不足k个,我们就输出整个字符串长度作为答案了。为什么不能呢,因为部分字母压根不足k个,假设它是字母‘a’。
那么不管我们的目标字符串长什么样,它必然不包含‘a’。那么我们可以用字母a作为分割符,把字符串分成若干段,继续进行判断。因为每次都是找到一些使当前判断字符串不成立的字母,
这样字母最多26个,所以26层循环就可以了。我门不断细分这些字符串,直到其长度为0或者满足条件记录长度。
判断满足性时间常数的,用一个大二维数组记录每个字母在每个位置出现次数就ok。
代码:
class Solution: def __init__(self): self.d=None self.k=0 def getNum(self,l,r): if l==0: return self.d[r][:] ans=[0]*26 for i in range(26): ans[i]=self.d[r][i]-self.d[l-1][i] return ans def noValid(self,a): ans=set() for i in range(26): if a[i]>0 and a[i]<self.k: ans.add(i) return ans def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ self.k=k l=len(s) if l==0: return 0 d=[[0]*26] d[-1][ord(s[0])-ord('a')]+=1 for i in range(1,l): d.append(d[-1][:]) d[-1][ord(s[i])-ord('a')]+=1 self.d=d next=[(0,l-1)] maxx=0 for _ in range(26): tem=[] for x,y in next: if x>y: continue n=self.getNum(x,y) nov=self.noValid(n) if len(nov)==0: maxx=max(maxx,y-x+1) continue last=x for i in range(x,y+1): if ord(s[i])-ord('a') in nov: tem.append((last,i-1)) last=i+1 tem.append((last,y)) next=tem return maxx