-
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)
, wherec
is a character andx
is a digit, that returns thexth
character afterc
.- For example,
shift('a', 5) = 'f'
andshift('x', 0) = 'x'
.
For every odd index
i
, you want to replace the digits[i]
withshift(s[i-1], s[i])
.Return
s
after replacing all digits. It is guaranteed thatshift(s[i-1], s[i])
will never exceed'z'
. - For example,
class Solution:
def replaceDigits(self, s: str) -> str:
d=len(s)
answer=""
for i in range(d):
# if the digit is in odd position(1,3,...),then we shift
if i % 2 == 1:
answer+=self.shift(s[i-1],int(s[i]))
# if in even position(0,2,4...),then we add it to the answer list
else:
answer+=s[i]
return answer
#create a 'shift' function to follow the requirement
def shift(self,char:str,index:int):
#use ascii to shift the char
return chr(ord(char)+index)
char * replaceDigits(char * s){
char* temp=s;
for (int i=0;i<strlen(s);i++)
{
if (i%2==1)
{
/*printf("%i ",i);*/
int index=(int) s[i]-48;
/*printf("%i\n",index);*/
s[i]=((int)s[i-1]+index);
}
}
return (temp);
}
{% hint style="info" %} One small but important thing here. For the 9th line, even though s[i] in this case is '1' or '3' or whatever number. When we convert it into an int it is going to give us its ascii number instead of giving us the number itself. Therefore we have to minus 48 from it. (ASCII for '1' is 49). {% endhint %}
For the C solution, there is another way to iterate the loop. Instead of writing
for (int i=0;s[i]!=NULL;i++) (WRONG METHOD!!!!!)
which will give us an warning information about comparing an interger with an pointer. We should be writing something like
for (int i=0;s[i]!=0;i++)
Here, 'NULL' is an pointer that is pointing nowhere. But it is still an pointer, while s[i] is stored as an ascii number so it is an int. Therefore comparing 'NULL' with s[i] will result in an warning.