Decrypt String from Alphabet to Integer Mapping — LeetCode 1309 Python Solution
- Problem
- #1309
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.