-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
longest-subsequence-repeated-k-times.cpp
59 lines (56 loc) · 1.46 KB
/
longest-subsequence-repeated-k-times.cpp
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
53
54
55
56
57
58
59
// Time: O(n * (n/k)!)
// Space: O(n)
class Solution {
public:
string longestSubsequenceRepeatedK(string s, int k) {
vector<int> cnts(26);
for (const auto& c : s) {
++cnts[c - 'a'];
}
string new_s;
for (const auto& c : s) {
if (cnts[c - 'a'] < k) {
continue;
}
new_s.push_back(c);
}
string result, curr;
backtracking(new_s, k, &curr, &cnts, &result);
return result;
}
private:
void backtracking(const string& s, int k, string *curr, vector<int> *cnts, string *result) {
if (!check(s, k, *curr)) {
return;
}
if (size(*curr) > size(*result)) {
*result = *curr;
}
for (char c = 'z'; c >= 'a'; --c) {;
if ((*cnts)[c -'a'] < k) {
continue;
}
(*cnts)[c -'a'] -= k;
curr->push_back(c);
backtracking(s, k, curr, cnts, result);
curr->pop_back();
(*cnts)[c -'a'] += k;
}
}
bool check(const string& s, int k, const string& curr) {
if (empty(curr)) {
return true;
}
int i = 0;
for (const auto& c: s) {
if (curr[i] != c || ++i != size(curr)) {
continue;
}
i = 0, --k;
if (k == 0) {
return true;
}
}
return false;
}
};