Longest Subsequence Repeated k Times LeetCode solution in Java

1
class Solution {
2
char[] A;
3

4
public String longestSubsequenceRepeatedK(String s, int k) {
5
A = s.toCharArray();
6
Queue<String> queue = new ArrayDeque<>();
7
queue.offer("");
8
String ans = "";
9
int[] count = new int[26];
10
BitSet bit = new BitSet();
11
for (char ch : A)
12
if (++count[ch - 'a'] >= k) {
13
bit.set(ch - 'a');
14
}
15
while (!queue.isEmpty()) {
16
String sb = queue.poll();
17
for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i + 1)) {
18
String res = sb + (char) (i + 'a');
19
if (check(k, res)) {
20
ans = res;
21
queue.offer(res);
22
}
23
}
24
}
25
return ans;
26
}
27

28
private boolean check(int k, String s) {
29
int cnt = 0;
30
for (char ch : A) {
31
if (s.charAt(cnt % s.length()) == ch && ++cnt >= k * s.length()) {
32
return true;
33
}
34
}
35
return false;
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0