EasyNo. 1309

Decrypt String from Alphabet to Integer Mapping — LeetCode 1309 Python Solution

Pattern
Hash Map
Topics
String
Reading time
2 min

The problem

You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively.

Example

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

Python solution

PythonSolution
class Solution:
    def freqAlphabets(self, s: str) -> str:
        ans = []
        i, n = 0, len(s)
        while i < n:
            if i + 2 < n and s[i + 2] == "#":
                ans.append(chr(int(s[i : i + 2]) + ord("a") - 1))
                i += 3
            else:
                ans.append(chr(int(s[i]) + ord("a") - 1))
                i += 1
        return "".join(ans)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1309. Decrypt String from Alphabet to Integer Mapping is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0006Zigzag ConversionMedium
0008String to Integer (atoi)Medium
0038Count and SayMedium
0058Length of Last WordEasy
0065Valid NumberHard
0068Text JustificationHard

Frequently asked questions

How hard is LeetCode 1309. Decrypt String from Alphabet to Integer Mapping?

LeetCode 1309. Decrypt String from Alphabet to Integer Mapping is rated Easy on LeetCode.

What is the time complexity of LeetCode 1309. Decrypt String from Alphabet to Integer Mapping?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1309. Decrypt String from Alphabet to Integer Mapping?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1309. Decrypt String from Alphabet to Integer Mapping cover?

LeetCode 1309. Decrypt String from Alphabet to Integer Mapping is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.