-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
longest-subsequence-repeated-k-times.py
52 lines (47 loc) · 1.34 KB
/
longest-subsequence-repeated-k-times.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Time: O(n * (n/k)!)
# Space: O(n)
import collections
class Solution(object):
def longestSubsequenceRepeatedK(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def check(s, k, curr):
if not curr:
return True
i = 0
for c in s:
if c != curr[i]:
continue
i += 1
if i != len(curr):
continue
i = 0
k -= 1
if not k:
return True
return False
def backtracking(s, k, curr, cnts, result):
if not check(s, k, curr):
return
if len(curr) > len(result):
result[:] = curr
for c in reversed(string.ascii_lowercase):
if cnts[c] < k:
continue
cnts[c] -= k
curr.append(c)
backtracking(s, k, curr, cnts, result)
curr.pop()
cnts[c] += k
cnts = collections.Counter(s)
new_s = []
for c in s:
if cnts[c] < k:
continue
new_s.append(c)
result =[]
backtracking(new_s, k, [], cnts, result)
return "".join(result)