题目

解题

def longestSubstring(s, k):
    # 如果字符串长度为0或者字符串长度小于k,返回0
    if len(s) == 0 or len(s) < k:
        return 0

    # 如果字符串中所有字符的出现次数都大于等于k,返回字符串的长度
    if all(s.count(char) >= k for char in set(s)):
        return len(s)

    # 否则进行分治
    for char in set(s):
        if s.count(char) < k:
            # 对字符串进行分割
            return max(longestSubstring(sub, k) for sub in s.split(char))

    return len(s)


# 示例
s = "aaabb"
k = 3
print(longestSubstring(s, k))  # 输出: 3, 因为最长子串是 "aaa"

s = "ababbc"
k = 2
print(longestSubstring(s, k))  # 输出: 5, 因为最长子串是 "ababb"
08-23 20:29