|
| 1 | +/** |
| 2 | + * 2182. Construct String With Repeat Limit |
| 3 | + * https://leetcode.com/problems/construct-string-with-repeat-limit/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a string s and an integer repeatLimit. Construct a new string |
| 7 | + * repeatLimitedString using the characters of s such that no letter appears more than |
| 8 | + * repeatLimit times in a row. You do not have to use all characters from s. |
| 9 | + * |
| 10 | + * Return the lexicographically largest repeatLimitedString possible. |
| 11 | + * |
| 12 | + * A string a is lexicographically larger than a string b if in the first position where |
| 13 | + * a and b differ, string a has a letter that appears later in the alphabet than the |
| 14 | + * corresponding letter in b. If the first min(a.length, b.length) characters do not differ, |
| 15 | + * then the longer string is the lexicographically larger one. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {string} s |
| 20 | + * @param {number} repeatLimit |
| 21 | + * @return {string} |
| 22 | + */ |
| 23 | +var repeatLimitedString = function(s, repeatLimit) { |
| 24 | + const frequency = new Array(26).fill(0); |
| 25 | + for (const char of s) { |
| 26 | + frequency[char.charCodeAt(0) - 97]++; |
| 27 | + } |
| 28 | + |
| 29 | + const result = []; |
| 30 | + let currentChar = 25; |
| 31 | + |
| 32 | + while (currentChar >= 0) { |
| 33 | + if (frequency[currentChar] === 0) { |
| 34 | + currentChar--; |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + const useCount = Math.min(frequency[currentChar], repeatLimit); |
| 39 | + for (let i = 0; i < useCount; i++) { |
| 40 | + result.push(String.fromCharCode(currentChar + 97)); |
| 41 | + } |
| 42 | + frequency[currentChar] -= useCount; |
| 43 | + |
| 44 | + if (frequency[currentChar] > 0) { |
| 45 | + let nextChar = currentChar - 1; |
| 46 | + while (nextChar >= 0 && frequency[nextChar] === 0) { |
| 47 | + nextChar--; |
| 48 | + } |
| 49 | + |
| 50 | + if (nextChar < 0) break; |
| 51 | + |
| 52 | + result.push(String.fromCharCode(nextChar + 97)); |
| 53 | + frequency[nextChar]--; |
| 54 | + } else { |
| 55 | + currentChar--; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return result.join(''); |
| 60 | +}; |
0 commit comments