Skip to main content
Back to problems
#1844
Easy Algorithms

Replace all digits with characters

String
82.7% acceptance
Feb 25, 2026
893
116
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. You must perform an operation shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'. For every odd index i, you want to replace the digit s[i] with the result of the shift(s[i-1], s[i]) operation. Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn replace_digits(s: String) -> String {
    let bytes = s.as_bytes();
    let mut result = Vec::with_capacity(bytes.len());
    for (i, &b) in bytes.iter().enumerate() {
      if i % 2 == 1 {
        // odd index: digit, shift previous letter
        let prev = result[i - 1];
        let digit = b - b'0';
        result.push(prev + digit);
      } else {
        result.push(b);
      }
    }
    String::from_utf8(result).unwrap()
  }
}