Alice is going to type target on her computer using a special keyboard that has only two keys:
Key 1 appends the character "a" to the string on the screen.
Key 2 changes the last character of the string on the screen to its next character in the English alphabet. For example, "c" changes to "d" and "z" changes to "a".
Note that initially there is an empty string "" on the screen, so she can only press key 1.
Return a list of all strings that appear on the screen as Alice types
target, in the order they appear, using the minimum key presses.
Input: target ="abc"Output: ["a","aa","ab","aba","abb","abc"]Explanation:
The sequence of key presses done by Alice are:* Press key 1, and the string on the screen becomes `"a"`.* Press key 1, and the string on the screen becomes `"aa"`.* Press key 2, and the string on the screen becomes `"ab"`.* Press key 1, and the string on the screen becomes `"aba"`.* Press key 2, and the string on the screen becomes `"abb"`.* Press key 2, and the string on the screen becomes `"abc"`.
To type the target string with the minimum key presses, always append ‘a’ until the next character can be reached by incrementing the last character. For each character, if it is ‘a’, append; otherwise, append ‘a’ and increment the last character as needed.
classSolution {
fungetSmallestSequence(target: String): List<String> {
val ans = mutableListOf<String>()
val s = StringBuilder()
for (c in target) {
if (s.isEmpty()) {
s.append('a')
ans.add(s.toString())
}
while (s.last() != c) {
s.setCharAt(s.length - 1, if (s.last() =='z') 'a'else s.last() + 1)
ans.add(s.toString())
}
if (s.length < target.length) {
s.append('a')
ans.add(s.toString())
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defgetSmallestSequence(self, target: str) -> list[str]:
ans = []
s =''for c in target:
ifnot s:
s +='a' ans.append(s)
while s[-1] != c:
s = s[:-1] + (chr(ord('a') if s[-1] =='z'else ord(s[-1]) +1))
ans.append(s)
if len(s) < len(target):
s +='a' ans.append(s)
return ans