用python写leetcode【13】 -- 至少有K个重复字符的最长子串(395)
2019-03-20 13:00
369 查看
至少有K个重复字符的最长子串(395)
题目
找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
示例 1:
输入:
s = “aaabb”, k = 3
输出:
3
最长子串为 “aaa” ,其中 ‘a’ 重复了 3 次。
示例 2:
输入:
s = “ababbc”, k = 2
输出:
5
最长子串为 “ababb” ,其中 ‘a’ 重复了 2 次, ‘b’ 重复了 3 次。
思路
采用分而治之的思想,对于一个字符串来说不满足的情况一定是有某些字母没有到达K次,所以在没有到达k次的点作为分隔符进行分割,分别隔成左右两部分继续上述操作,由于无论分割的顺序如何,最后得出的结果必然都是一致的,因此不需要遍历所有的不同字母分割,找到一个不满足的字符就可以进行分割。
代码
class Solution: def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ for i in set(s): if s.count(i) < k: # 找出不满足k次的字母 return max(self.longestSubstring(m, k) for m in s.split(i)) # 将其作为分割点进行分治 return len(s)
相关文章推荐
- Leetcode:395至少有K个重复字符的最长子串(C++)
- leetcode 395. 至少有K个重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- leetcode-无重复字符的最长子串(python)
- LeetCode3. 无重复字符的最长子串(python)
- Leetcode 刷题(python)之 无重复字符的最长子串
- leetcode之3. 无重复字符的最长子串python实现
- LeetCode题解(python)-3.无重复字符的最长子串
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- Leetcode 3. 无重复字符的最长子串
- [LeetCode] 395. Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
- LeetCode 无重复字符的最长子串
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- LeetCode 3. Longest Substring Without Repeating Characters 无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- C#leetcode刷题3无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(Java)
- 转 leetcode ——无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串