March-395. The longest substring with at least K repeated characters

 

class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        
        #如果字符串的长度是小于k的直接返回0
        if len(s)<k:
            return 0

        #遍历该字符串
        for c in set(s):
            #如果该字符的出现次数小于k,那么一定不能在子字符串中出现
            #所以根据该字符串将s切分,然后遍历每个子串,再去找最长子串的长度
            if s.count(c)<k:
                return max(self.longestSubstring(t,k) for t in s.split(c))

        #如果字符出现次数都大于等于k直接返回字符串的长度即可
        return len(s)
  • First observe the length of the string and K to judge
  • Traverse the characters in the string, if the number of occurrences of the character is less than k, then split the string into substrings, and then recursively find the length of the longest substring 

 

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/114279233