Similar Problems

Similar Problems not available

Replace All Digits With Characters - Leetcode Solution

Companies:

LeetCode:  Replace All Digits With Characters Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

You are given a string s containing digits from 0-9 and lowercase alphabet characters. Convert all digits in s to lowercase letters.

The replacement should be done in such a way that each digit i is replaced by characters[i - 1].

Return s after replacing all digits. It is guaranteed that s only contains digits and lowercase English letters.

Input: s = "a1b2c3d4e" Output: "abbdcfdhe" Explanation: The digits are replaced as follows:

  • 1 with 'a' in characters.
  • 2 with 'b' in characters.
  • 3 with 'c' in characters.
  • 4 with 'd' in characters. After replacing the digits, we get "abbdcfdhe".

Solution:

  • One approach to solve this problem is to use a for loop to iterate through the characters in the string s and at each iteration we would check if the character is a digit or not.

  • If the character is a digit, we would replace it with the corresponding lowercase letter from the characters array and add it to the result string.

  • If the character is not a digit, we would simply add it to the result string.

  • After iterating through the entire string, we would return the result string.

  • The implementation of the above algorithm in python is given below:

      class Solution:
          def replaceDigits(self, s: str) -> str:
              result = ""
              characters = "abcdefghijklmnopqrstuvwxyz"
              for i in range(len(s)):
                  if s[i].isdigit():
                      index = int(s[i]) - 1
                      result += characters[index]
                  else:
                      result += s[i]
              return result
    
  • In the above implementation, we have used the isdigit() method to check if the current character is a digit or not.

  • If the character is a digit, we have used the int() function to convert the character to an integer and subtracted 1 from it to get the corresponding index in the characters array.

  • We have then added the corresponding character to the result string.

  • If the character is not a digit, we have simply added it to the result string.

  • Finally, we have returned the result string.

  • The time complexity of this algorithm is O(n), where n is the length of the string s, as we are iterating through the string once.

  • The space complexity of this algorithm is also O(n), as we are using an additional result string of length n to store the final string after replacing the digits.

Replace All Digits With Characters Solution Code

1