Skip to content

Latest commit

 

History

History
84 lines (58 loc) · 2.58 KB

1844.-replace-all-digits-with-characters.md

File metadata and controls

84 lines (58 loc) · 2.58 KB

1844. Replace All Digits with Characters

  • 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'.

Solution (Python)

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)

Solution (C)

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 %}

P.S.

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.