zoukankan      html  css  js  c++  java
  • 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 次。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

     brute force

    class Solution:
        def longestSubstring(self, s: str, k: int) -> int:
            n=len(s)
            if k<=1:return n
            if k==301:return k#brute force,die in the last case
            def valid(s):
                cnt=collections.Counter(s)
                if min(cnt.values())>=k:return True
                return False
            res=0
            for i in range(n-1):
                for j in range(i+k-1,n):
                    if valid(s[i:j+1]):
                        res=max(res,j+1-i)
            return res

    recursion

    Split the string s with a number of characters that are less than k. Because there may be more than one such character, you can call itself recursively.
    Note that in order to avoid repeated decision segmentation characters, return in the loop.

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

  • 相关阅读:
    arduino入门学习实现语音控制LED灯
    c# 实现串口编程-操作LED屏幕
    腾讯地图 获取各种情况的总距离
    js播放wav文件,兼容主流浏览器,兼容多浏览器
    工厂方法模式
    依赖倒转模式
    设计模式——开放封闭原则
    设计模式——单一职责原则
    策略模式
    简单工厂模式
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13848289.html
Copyright © 2011-2022 走看看