• 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)
            

  • 相关阅读:
    hadoop面试时的一些问题解答
    FTRL(Follow The Regularized Leader)学习总结
    循环神经(LSTM)网络学习总结
    深度学习中常用的激活函数
    TF.learn学习
    TensorFlow实现分布式计算
    TensorFlow TensorBoard使用
    深度学习总结
    Spark SQL相关总结
    推荐系统/广告系统索引目录
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13848289.html
Copyright © 2020-2023  润新知