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 shift(c, x)
, where c
is a character and x
is a digit, that shifts c
forward by x
positions in the alphabet. For example, shift('a', 1) = 'b'
and shift('x', 3) = 'a'
.
Replace every digit in s
with the character it shifts to and return the resulting string.
s
is empty?
s
to a list of characters to allow for mutable operations.shift
function to shift the character by the numeric value and replace the digit at the respective odd index with the shifted character.n
is the length of the string s
, since we are iterating through the string once and performing constant-time operations inside the loop.def shift(c, x):
return chr(ord(c) + x)
def replaceDigits(s: str) -> str:
chars = list(s)
for i in range(1, len(chars), 2):
chars[i] = shift(chars[i-1], int(chars[i]))
return ''.join(chars)
# Example usage:
s = "a1c1e1"
print(replaceDigits(s)) # Output: "abcdef"
In this solution:
shift
function calculates the new character by converting the character to its ASCII value using ord(c)
, adding the digit x
, and converting back to a character using chr()
.replaceDigits
function iterates over the string, performing the necessary transformations and returns the modified string.This approach ensures that we correctly replace all digits in the string with their corresponding shifted characters efficient.
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?