Skip to content

Commit 14feed3

Browse files
authored
Create 2014. Longest Subsequence Repeated k Times
1 parent 52d11dd commit 14feed3

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public:
3+
bool isKRepeatedSubsequence(const string& s, const string& pattern, int k) {
4+
int pos = 0, matched = 0;
5+
int m = pattern.size();
6+
7+
for (char ch : s) {
8+
if (ch == pattern[pos]) {
9+
pos++;
10+
if (pos == m) {
11+
pos = 0;
12+
matched++;
13+
if (matched == k) return true;
14+
}
15+
}
16+
}
17+
return false;
18+
}
19+
20+
string longestSubsequenceRepeatedK(string s, int k) {
21+
vector<int> freq(26, 0);
22+
for (char ch : s) freq[ch - 'a']++;
23+
24+
vector<char> candidates;
25+
for (int i = 25; i >= 0; --i) {
26+
if (freq[i] >= k) candidates.push_back('a' + i);
27+
}
28+
29+
queue<string> q;
30+
string ans = "";
31+
32+
for (char ch : candidates) {
33+
q.push(string(1, ch));
34+
}
35+
36+
while (!q.empty()) {
37+
string curr = q.front(); q.pop();
38+
39+
if (curr.size() > ans.size() || (curr.size() == ans.size() && curr > ans)) {
40+
if (isKRepeatedSubsequence(s, curr, k)) ans = curr;
41+
}
42+
43+
if (curr.size() == 7) continue;
44+
45+
for (char ch : candidates) {
46+
string next = curr + ch;
47+
if (isKRepeatedSubsequence(s, next, k)) q.push(next);
48+
}
49+
}
50+
51+
return ans;
52+
}
53+
};

0 commit comments

Comments
 (0)