|
| 1 | +/** |
| 2 | + * @param {string} s |
| 3 | + * @param {number} k |
| 4 | + * @return {string} |
| 5 | + */ |
| 6 | +var longestSubsequenceRepeatedK = function(s, k) { |
| 7 | + // Max length of the subsequence can be determined by the length of the string and k |
| 8 | + const maxLen = Math.floor(s.length / k); |
| 9 | + |
| 10 | + // Find all possible characters that can appear in the subsequence (characters must appear at |
| 11 | + // least k times in s) |
| 12 | + const charCount = new Map(); |
| 13 | + const possibleChars = [] |
| 14 | + |
| 15 | + for (const char of s) { |
| 16 | + if (charCount.has(char)) { |
| 17 | + charCount.set(char, charCount.get(char) + 1); |
| 18 | + } else { |
| 19 | + charCount.set(char, 1); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + for (const char of charCount.keys()) { |
| 24 | + if (charCount.get(char) >= k) { |
| 25 | + possibleChars.push(char); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // Test possibilities |
| 30 | + let ans = ""; |
| 31 | + dfs(""); |
| 32 | + |
| 33 | + return ans; |
| 34 | + |
| 35 | + // Recursive function, tests if the given subsequence repeats k times in s |
| 36 | + function dfs(seq) { |
| 37 | + // Does not have enough repeats, return |
| 38 | + if (countRepeats(seq) < k) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // Update our answer if the new subsequence is better |
| 43 | + if (seq.length > ans.length || (seq.length === ans.length && seq > ans)) { |
| 44 | + ans = seq; |
| 45 | + } |
| 46 | + |
| 47 | + // Append possible characters to the subsequence and test again |
| 48 | + if (seq.length < maxLen) { |
| 49 | + for (const char of possibleChars) { |
| 50 | + dfs(seq + char); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // Counts the number of times the given subsequence repeats in s (up to k) |
| 56 | + function countRepeats(seq) { |
| 57 | + |
| 58 | + // Empty string, return k |
| 59 | + if (!seq) { |
| 60 | + return k; |
| 61 | + } |
| 62 | + |
| 63 | + let repeats = 0; |
| 64 | + let seqIdx = 0; |
| 65 | + |
| 66 | + for (const char of s) { |
| 67 | + if (char === seq[seqIdx]) { |
| 68 | + seqIdx += 1; |
| 69 | + |
| 70 | + if (seqIdx >= seq.length) { |
| 71 | + seqIdx = 0; |
| 72 | + repeats += 1; |
| 73 | + |
| 74 | + if (repeats >= k) { |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return repeats; |
| 82 | + } |
| 83 | +}; |
0 commit comments