题:https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/
题目
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.
思路
题目大意
一个字符串 Str,都是由 小写字母组成。找出一个最长子串 subStr,这子串包含的 字符在子串中出现的次数大于等于 k。
解题思路
总体思路将 整体求解 分解为 局部求解。
- 对于 字符串 s。统计字符串 s 中字符出现次数 小于 k的字符,将字符放入 fliterSet 集合中。
- 若 fliterSet 中元素为空,那么 s 中 符合要求的 最大子串 就是 s本身,长度为 len(s)。否则,用 fliterSet 的元素将 s分割,将切割的多个子字符串strLst。将strLst中的每个 字符串 进行 1中的处理,获得 最长子串数。
Note:
代码 1 比较 简洁,代码 2 便于 理解。都是实现上面的思路。
code
1
class Solution:
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if len(s) == 0:
return 0
counter = {}
for i in range(len(s)):
if s[i] in counter.keys():
counter[s[i]] += 1
else:
counter[s[i]] = 1
filter_set = set()
for key in counter.keys():
if counter[key] < k:
filter_set.add(key)
if len(filter_set) == 0:
return len(s)
subsmaxlen = 0
starti = 0
i = 0
while i < len(s):
if s[i] in filter_set:
if starti != i:
subsmaxlen = max(subsmaxlen, self.longestSubstring(s[starti:i], k))
starti = i+1
i += 1
if i - starti >0:
subsmaxlen = max(subsmaxlen, self.longestSubstring(s[starti:i], k))
return subsmaxlen
2
class Solution:
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
counter = {}
for i in range(len(s)):
if s[i] in counter.keys():
counter[s[i]] += 1
else:
counter[s[i]] = 1
filter_set = set()
for key in counter.keys():
if counter[key] < k:
filter_set.add(key)
if len(filter_set) == 0:
return len(s)
slst = list(s)
for i in range(len(slst)):
if slst[i] in filter_set:
slst[i] = '#'
subsmaxlen = 0
substring = "".join(slst).split("#")
for i in range(len(substring)):
subsmaxlen = max(subsmaxlen, self.longestSubstring(substring[i], k))
return subsmaxlen