Pankaj Tanwar
Published on

Replace All Digits with Characters.

––– views

Hey-yo, It's Monday, Oct. 11. Day 24 of my coding diary.

Problem of the day - Replace All Digits with Characters

Tag - Easy

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 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 shift(s[i-1], s[i]).

Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.

Example 1:

Input: s = "a1c1e1" Output: "abcdef"


The Problem is pretty straightforward. It's just one should be aware of the hex code of digits.

The important thing here is to convert the digit to the integer value. Digit '0' is equal to 48 in integer so I can take advantage of this information to quickly solve this problem.

class Solution {
public:
string replaceDigits(string s) {
for(int i=1;i<s.length();i+=2) {
s[i] = s[i-1] + int(s[i]) - 48;
}
return s;
}
};

Let's improvee the code a bit.

Here is my short and sweet code

class Solution {
public:
string replaceDigits(string s) {
for(int i=1;i<s.length();i+=2) {
s[i] += s[i-1] - '0';
}
return s;
}
};

Ahm ahm, seems, gradually, I am improving on my code writing style. Such a neat and clean code, oh gosh!

Enough of bragging about myself.

I hit submit and as expected, 0 ms runtime and faster than 100% of C++ submission.

That was a really nice problem. A quick refresher on the basics of strings.

Please do let me know if you have some other approach to share.


Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.


You might like previous editions of my coding diary