Leetcode 1844. Replace All Digits with Characters
You are given a zero-indexed string s
that has lowercase English letters in its even indices and digits in its odd indices.
There is a function shift(c, x)
, where c
is a character and x
is a digit, that shifts c
forward in the alphabet x
times. For example, shift('a', 1)
= ‘b’ and shift('x', 2)
= ‘z’.
Return the final string after applying shift
to all the digits in s
.
s
is even and ranges from 1 to 1000.s
contains only lowercase English letters and digits.s
. Each character in the string is processed once.#include <iostream>
#include <string>
using namespace std;
string replaceDigits(string s) {
for (int i = 1; i < s.size(); i += 2) {
int digit = s[i] - '0'; // Convert character at odd index to corresponding digit
s[i] = s[i - 1] + digit; // Shift the preceding character
}
return s;
}
// Main function to test the implementation
int main() {
string input = "a1b2c3d4e";
cout << "Original String: " << input << endl;
string result = replaceDigits(input);
cout << "Transformed String: " << result << endl;
return 0;
}
The replaceDigits
function iterates through the string, checking for digits at odd indices, converts each to an integer, shifts the preceding character accordingly, and updates the string in place. The main function demonstrates how to use this utility with an example.
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?