|
3 | 3 | * @param {number} k
|
4 | 4 | * @return {string}
|
5 | 5 | */
|
6 |
| -const smallestBeautifulString = function(s, k) { |
7 |
| -const chars = s.split('') |
| 6 | +const smallestBeautifulString = function (s, k) { |
| 7 | + const chars = s.split('') |
8 | 8 |
|
9 |
| -for (let i = chars.length - 1; i >= 0; i--) { |
10 |
| - chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1) |
11 |
| - while (containsPalindrome(chars, i)) { |
| 9 | + for (let i = chars.length - 1; i >= 0; i--) { |
12 | 10 | chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1)
|
| 11 | + while (containsPalindrome(chars, i)) { |
| 12 | + chars[i] = String.fromCharCode(chars[i].charCodeAt(0) + 1) |
| 13 | + } |
| 14 | + if (chars[i] < String.fromCharCode('a'.charCodeAt(0) + k)) { |
| 15 | + // If s[i] is among the first k letters, then change the letters after |
| 16 | + // s[i] to the smallest ones that don't form any palindrome substring. |
| 17 | + return changeSuffix(chars, i + 1) |
| 18 | + } |
13 | 19 | }
|
14 |
| - if (chars[i] < String.fromCharCode('a'.charCodeAt(0) + k)) { |
15 |
| - // If s[i] is among the first k letters, then change the letters after |
16 |
| - // s[i] to the smallest ones that don't form any palindrome substring. |
17 |
| - return changeSuffix(chars, i + 1) |
18 |
| - } |
19 |
| -} |
20 | 20 |
|
21 |
| -return '' |
| 21 | + return '' |
22 | 22 |
|
23 |
| -// Returns true if chars[0..i] contains palindrome. |
24 |
| -function containsPalindrome(chars, i) { |
25 |
| - return ( |
26 |
| - (i > 0 && chars[i] == chars[i - 1]) || (i > 1 && chars[i] == chars[i - 2]) |
27 |
| - ) |
28 |
| -} |
| 23 | + // Returns true if chars[0..i] contains palindrome. |
| 24 | + function containsPalindrome(chars, i) { |
| 25 | + return ( |
| 26 | + (i > 0 && chars[i] == chars[i - 1]) || (i > 1 && chars[i] == chars[i - 2]) |
| 27 | + ) |
| 28 | + } |
29 | 29 |
|
30 |
| -// Returns string where chars[i..] replaced with the smallest letters that |
31 |
| -// don't form any palindrome substring. |
32 |
| -function changeSuffix(chars, i) { |
33 |
| - for (let j = i; j < chars.length; j++) { |
34 |
| - chars[j] = 'a' |
35 |
| - while (containsPalindrome(chars, j)) { |
36 |
| - chars[j] = String.fromCharCode(chars[j].charCodeAt(0) + 1) |
| 30 | + // Returns string where chars[i..] replaced with the smallest letters that |
| 31 | + // don't form any palindrome substring. |
| 32 | + function changeSuffix(chars, i) { |
| 33 | + for (let j = i; j < chars.length; j++) { |
| 34 | + chars[j] = 'a' |
| 35 | + while (containsPalindrome(chars, j)) { |
| 36 | + chars[j] = String.fromCharCode(chars[j].charCodeAt(0) + 1) |
| 37 | + } |
37 | 38 | }
|
| 39 | + return chars.join('') |
38 | 40 | }
|
39 |
| - return chars.join('') |
40 | 41 | }
|
41 |
| - |
42 |
| -}; |
0 commit comments