Skip to content

Commit 1bcc5fc

Browse files
authored
Update 2663-lexicographically-smallest-beautiful-string.js
1 parent e0f66a7 commit 1bcc5fc

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

2663-lexicographically-smallest-beautiful-string.js

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,39 @@
33
* @param {number} k
44
* @return {string}
55
*/
6-
const smallestBeautifulString = function(s, k) {
7-
const chars = s.split('')
6+
const smallestBeautifulString = function (s, k) {
7+
const chars = s.split('')
88

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--) {
1210
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+
}
1319
}
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-
}
2020

21-
return ''
21+
return ''
2222

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+
}
2929

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+
}
3738
}
39+
return chars.join('')
3840
}
39-
return chars.join('')
4041
}
41-
42-
};

0 commit comments

Comments
 (0)