3324. Find the Sequence of Strings Appeared on the Screen
You are given a string target
.
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.
Example 1:
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"
.
Example 2:
Input: target = "he"
Output: ["a","b","c","d","e","f","g","h","ha","hb","hc","hd","he"]
Constraints:
1 <= target.length <= 400
target
consists only of lowercase English letters.
Solution:
// class Solution {
// public List<String> stringSequence(String target) {
// List<String> result = new ArrayList<String>();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < target.length(); i++){
// char cur = target.charAt(i);
// char start = 'a';
// sb.append(start);
// result.add(sb.toString());
// while(start != cur){
// start++;
// sb.replace(i, )
// }
// }
// }
// }
class Solution {
public List<String> stringSequence(String target) {
List<String> result = new ArrayList<>();
StringBuilder screen = new StringBuilder();
for (char targetChar : target.toCharArray()) {
// Step 1: Press key 1 to add 'a' to the current string
screen.append('a');
result.add(screen.toString()); // Add the string after appending 'a'
// Step 2: Change the last character to match the target character
while (screen.charAt(screen.length() - 1) != targetChar) {
// Press Key 2 to change the last character
char lastChar = screen.charAt(screen.length() - 1);
lastChar = lastChar == 'z' ? 'a' : (char)(lastChar + 1); // Loop from 'z' to 'a'
screen.setCharAt(screen.length() - 1, lastChar);
result.add(screen.toString()); // Add each intermediate state
}
}
return result;
}
}
/*
key1: -> "a"
key2: next alphabet
Note that initially there is an empty string "" on the screen, so she can only press key 1.
-> start from a
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.
minimum key presses
he -> a
*/