207 - 395 至少有K个重复字符的最长子串

题目

找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。

示例 1:

输入: s = "aaabb", k = 3

输出: 3

最长子串为 "aaa" ,其中 'a' 重复了 3 次。

示例 2:

输入: s = "ababbc", k = 2

输出: 5

最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。

解答

https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python

class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        for c in set(s):
            if s.count(c) < k:
                return max(Solution.longestSubstring(self, t, k) for t in s.split(c))
        return len(s)

Runtime: 40 ms, faster than 31.36% of Python3 online submissions for Longest Substring with At Least K Repeating Characters.

Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Longest Substring with At Least K Repeating Characters.

Last updated

Was this helpful?