Leetcode 1844. Replace All Digits with Characters
1844. Replace All Digits with Characters
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.
There is a function defined as shift(c, x) where c is a character and x is a digit, that shifts c forward in the alphabet by x positions.
shift('a', 1) = 'b' and shift('x', 3) = 'a'.Replace every digit in s with shift(s[i-1], s[i]).
Return the modified string s.
Example 1:
Input: s = "a1c1e1"
Output: "abcdef"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a', 1) = 'b'
- s[3] -> shift('c', 1) = 'd'
- s[5] -> shift('e', 1) = 'f'
Example 2:
Input: s = "a1b2c3d4e"
Output: "abbdcfdhe"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a', 1) = 'b'
- s[3] -> shift('b', 2) = 'd'
- s[5] -> shift('c', 3) = 'f'
- s[7] -> shift('d', 4) = 'h'
To solve this problem, follow these steps:
StringBuilder to construct the final string.s.StringBuilder.shift function.StringBuilder.StringBuilder to a final string and return it.Helper Method:
shift(char c, int x): This method takes a character c and an integer x, then returns the character shifted x positions forward in the alphabet.public class ReplaceDigitsWithCharacters {
public static void main(String[] args) {
String s1 = "a1c1e1";
String s2 = "a1b2c3d4e";
System.out.println(replaceDigits(s1)); // Output: "abcdef"
System.out.println(replaceDigits(s2)); // Output: "abbdcfdhe"
}
public static String replaceDigits(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (i % 2 == 0) {
result.append(currentChar);
} else {
int shiftValue = currentChar - '0';
char previousChar = s.charAt(i - 1);
char shiftedChar = shift(previousChar, shiftValue);
result.append(shiftedChar);
}
}
return result.toString();
}
private static char shift(char c, int x) {
return (char) (c + x);
}
}
n is the length of the string s. We iterate through the string once.StringBuilder to store the resulting string.This solution is efficient for the given problem and adheres to the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?