Decrypt String from Alphabet to Integer Mapping in Python


Suppose we have a string s that is formed by digits ('0' - '9') and '#'. We have to map s to one English lowercase characters as follows −

  • Characters ('a' to 'i') are represented by ('1' to '9') respectively.

  • Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.

We have to find the string formed after mapping. We are taking one assumption that a unique mapping will always exist. So if the input is like “10#11#12”, then it will be “jkab”. As 10# is j, 11# is k, 1 is a and 2 is b.

To solve this, we will follow these steps −

  • create one map to hold all characters and their corresponding ASCII values

  • ans := 0, and map[‘’] := ‘’, ad i := length of string – 1

  • while i > 0

    • if s[i] is #, then

      • temp := “”

      • for j := i – 2 to i, temp := temp + s[j]

      • ans := map[temp] + ans

      • decrease i by 3

    • otherwise ans := map[s[i]] + ans, and decrease i by 1

  • return ans

Example (Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def freqAlphabets(self, s):
      m = {}
      x = 'a'
      for i in range(1, 27):
         m[str(i)] = x
         x = chr(ord(x) + 1)
      ans = ""
      m['']=''
      i = len(s) - 1
      while i >= 0:
         if s[i] == "#":
            temp = ""
            for j in range(i - 2, i):
               temp += s[j]
            ans = m[str(temp)] + ans
            i -= 3
         else:
            ans = m[s[i]] + ans
            i -= 1
      return ans
ob1 = Solution()
print(ob1.freqAlphabets("17#123#5621#"))

Input

"17#123#5621#"

Output

qawefu

Updated on: 27-Apr-2020

554 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements