2663. Lexicographically Smallest Beautiful String
Description
A string is beautiful if:
- It consists of the first
k
letters of the English lowercase alphabet. - It does not contain any substring of length
2
or more which is a palindrome.
You are given a beautiful string s
of length n
and a positive integer k
.
Return the lexicographically smallest string of length n
, which is larger than s
and is beautiful. If there is no such string, return an empty string.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
.
- For example,
"abcd"
is lexicographically larger than"abcc"
because the first position they differ is at the fourth character, andd
is greater thanc
.
Example 1:
Input: s = "abcz", k = 26 Output: "abda" Explanation: The string "abda" is beautiful and lexicographically larger than the string "abcz". It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda".
Example 2:
Input: s = "dc", k = 4 Output: "" Explanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.
Constraints:
1 <= n == s.length <= 105
4 <= k <= 26
s
is a beautiful string.
Solutions
Solution 1: Greedy
We can find that a palindrome string of length $2$ must have two adjacent characters equal; and a palindrome string of length $3$ must have two characters at the beginning and end equal. Therefore, a beautiful string does not contain any palindrome substring of length $2$ or longer, which means that each character in the string is different from its previous two adjacent characters.
We can greedily search backwards from the last index of the string, find an index $i$ such that the character at index $i$ can be replaced by a slightly larger character, while ensuring that it is different from its two previous adjacent characters.
- If such an index $i$ is found, then we replace $s[i]$ with $c$, and replace the characters from $s[i+1]$ to $s[n-1]$ with the characters in the first $k$ characters of the alphabet in the order of the minimum dictionary that are not the same as the previous two adjacent characters. After the replacement is completed, we obtain a beautiful string that is the smallest in the dictionary and greater than $s$.
- If such an index $i$ cannot be found, then we cannot construct a beautiful string greater than $s$ in dictionary order, so return an empty string.
The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|