今天做了一道算法題 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)