LeetCode 1844: Replace All Digits with Characters

String

Problem Description

Explanation:

To solve this problem, we iterate through the characters in the input string s. When we encounter a digit at an odd index, we replace it with the result of the shift operation using the previous character at the even index. The shift operation simply shifts a character by a given number of positions. We can implement the shift operation by adding the ASCII value of the character and the given digit, and then converting it back to a character.

Algorithmic Idea:

  1. Iterate through the characters of the input string s.
  2. When encountering a digit at an odd index, replace it with the result of the shift operation using the previous character.
  3. Implement the shift operation by adding the ASCII value of the character and the digit, and converting it back to a character.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string s.

Space Complexity:

The space complexity is O(n) as well, to store the resulting string.

Solutions

class Solution {
    public String replaceDigits(String s) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i))) {
                result.append(shift(s.charAt(i - 1), s.charAt(i) - '0'));
            } else {
                result.append(s.charAt(i));
            }
        }
        return result.toString();
    }

    private char shift(char c, int x) {
        return (char) (c + x);
    }
}

Loading editor...