LeetCode-in-Java

3324. Find the Sequence of Strings Appeared on the Screen

Medium

You are given a string target.

Alice is going to type target on her computer using a special keyboard that has only two keys:

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:

Example 2:

Input: target = “he”

Output: [“a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”,”ha”,”hb”,”hc”,”hd”,”he”]

Constraints:

Solution

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> stringSequence(String t) {
        List<String> ans = new ArrayList<>();
        int l = t.length();
        StringBuilder cur = new StringBuilder();
        for (int i = 0; i < l; i++) {
            char tCh = t.charAt(i);
            cur.append('a');
            ans.add(cur.toString());
            while (cur.charAt(i) != tCh) {
                char lastCh = cur.charAt(i);
                char nextCh = (char) (lastCh == 'z' ? 'a' : lastCh + 1);
                cur.setCharAt(i, nextCh);
                ans.add(cur.toString());
            }
        }
        return ans;
    }
}