Skip to content

1844. Replace All Digits with Characters 👍

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  string replaceDigits(string s) {
    for (int i = 1; i < s.length(); i += 2)
      s[i] += s[i - 1] - '0';
    return s;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public String replaceDigits(String s) {
    char[] chars = s.toCharArray();
    for (int i = 1; i < chars.length; i += 2)
      chars[i] += chars[i - 1] - '0';
    return String.valueOf(chars);
  }
}
1
2
3
4
5
6
class Solution:
  def replaceDigits(self, s: str) -> str:
    return ''.join(
        c if i % 2 == 0 else chr(ord(s[i - 1]) + int(c))
        for i, c in enumerate(s)
    )