-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2014_Longest_Subsequence_Repeated_K_Times.c++
More file actions
56 lines (51 loc) · 1.37 KB
/
2014_Longest_Subsequence_Repeated_K_Times.c++
File metadata and controls
56 lines (51 loc) · 1.37 KB
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
class Solution {
public:
string longestSubsequenceRepeatedK(string s, int k) {
vector<int> freq(26);
for (char ch : s) {
freq[ch - 'a']++;
}
vector<char> candidate;
for (int i = 25; i >= 0; i--) {
if (freq[i] >= k) {
candidate.push_back('a' + i);
}
}
queue<string> q;
for (char ch : candidate) {
q.push(string(1, ch));
}
string ans = "";
while (!q.empty()) {
string curr = q.front();
q.pop();
if (curr.size() > ans.size()) {
ans = curr;
}
for (char ch : candidate) {
string next = curr + ch;
if (isKRepeatedSubsequence(s, next, k)) {
q.push(next);
}
}
}
return ans;
}
bool isKRepeatedSubsequence(const string& s, const string& t, int k) {
int pos = 0, matched = 0;
int n = s.size(), m = t.size();
for (char ch : s) {
if (ch == t[pos]) {
pos++;
if (pos == m) {
pos = 0;
matched++;
if (matched == k) {
return true;
}
}
}
}
return false;
}
};