LeetCode 3324: Find the Sequence of Strings Appeared on the Screen

StringSimulation

Problem Description

Explanation

To solve this problem, we can simulate the process of typing the target string using the given rules. We start with an empty string on the screen and apply the key presses based on the characters in the target string. We keep track of the current string on the screen and update it according to the rules mentioned. By doing so, we can generate all possible strings that appear on the screen as Alice types the target string with the minimum key presses.

  • Initialize an empty list to store the strings that appear on the screen.
  • Start with an empty string on the screen.
  • For each character in the target string:
    • If the character is not equal to the last character on the screen, append a new character to the screen.
    • Otherwise, change the last character on the screen to the next character in the English alphabet.
  • Add each updated string on the screen to the list.
  • Return the list of strings that appeared on the screen.

Time Complexity: O(n), where n is the length of the target string. Space Complexity: O(n), for storing the list of strings.

Solutions

class Solution {
    public List<String> findTheSequence(String target) {
        List<String> result = new ArrayList<>();
        String screen = "";
        
        for (char c : target.toCharArray()) {
            if (screen.isEmpty() || screen.charAt(screen.length() - 1) != c) {
                screen += c;
            } else {
                screen = screen.substring(0, screen.length() - 1) + (char)(c + 1);
            }
            result.add(screen);
        }
        
        return result;
    }
}

Loading editor...