【leetcode】395. Longest Substring with At Least K Repeating Characters

题目如下:

解题思路:题目要找出一段连续的子串内所有字符出现的次数必须要大于k,因此出现次数小于k的字符就一定不能出现,所以就可以以这些字符作为分隔符分割成多个子串,然后继续对子串递归,找出符合条件的子串。

代码如下:

class Solution(object):
    res = 0
    def splitToSubs(self,subs,k):
        dic = {}
        for i in subs:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1
        exclusive = []
        for i, v in enumerate(subs):
            if dic[v] < k:
                exclusive.append(i)
        if len(exclusive) == 0:
            self.res = max(self.res,len(subs))
            return
        start, end = 0, len(subs) - 1
        for i in (exclusive):
            if i - start < k:
                start = i
                continue
            else:
                tmp = subs[start:i]
                self.splitToSubs(tmp,k)
                start = i
        if end - exclusive[-1] >= k:
            self.splitToSubs(subs[exclusive[-1] + 1:end + 1],k)
    def longestSubstring(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        self.res = 0
        self.splitToSubs(s,k)
        return self.res

 

posted @ 2018-09-19 11:18  seyjs  阅读(271)  评论(0编辑  收藏  举报