Leetcode - Decrypt String from Alphabet to Integer Mapping Solution

Given a string s formed by digits ('0' - '9') and '#' . We want to map s to 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.

Return the string formed after mapping.

It's guaranteed that a unique mapping will always exist.

Example 1:

Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

Example 2:

Input: s = "1326#"
Output: "acz"

Example 3:

Input: s = "25#"
Output: "y"

Example 4:

Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
Output: "abcdefghijklmnopqrstuvwxyz"

Constraints:

  • 1 <= s.length <= 1000
  • s[i] only contains digits letters ('0'-'9') and '#' letter.
  • s will be valid string such that mapping is always possible.

Solution in Python

from collections import defaultdict,deque
class Solution:
    def freqAlphabets(self, s: str) -> str:
        index = -1
        arr = deque()
        while (len(s)+index)>-1:
            if s[index]=="#":
                arr.appendleft(s[index-2:index+1 or len(s)])
                index-=3
            else:
                arr.appendleft(s[index])
                index-=1
        hash_map = defaultdict(str)
        for x,y in zip(range(1,10),range(ord("a"), ord("i")+1)):
            hash_map[str(x)]= chr(y)
        for x,y in zip(range(10,27),range(ord("j"), ord("z")+1)):
            hash_map[str(x)+"#"]= chr(y)
        return "".join((map(lambda x : hash_map[x], arr)))

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe