今天做了一道算法题 https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
我的C++实现是暴力算法,思路比较简单,O(n2)算法复杂度。我看leetcode里面的讨论,下面这个思路不错,是O(n)算法复杂度。
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
他的代码采用递归:找到第一个出现次数不到k次的字符,将字符串分成两半,然后对两半分别递归得到结果。不过,下面这段python代码写的更漂亮,只有4行代码,把上面这个C++的算法表达的非常完美。不得不感叹python处理字符串功能的强大以及语法之灵活!
class Solution:
def longestSubstring(self, s, k):
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)