Decrypt String from Alphabet to Integer Mapping Problem
Description
LeetCode Problem 1309.
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. - Characters (
'j'to'z') are represented by ('10#'to'26#') respectively.
Return the string formed after mapping.
The test cases are generated so 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"
Constraints:
1 <= s.length <= 1000sconsists of digits and the'#'letter.swill be a valid string such that mapping is always possible.
Solution
Approach: Look Two Characters Ahead
Read the string from left to right. At position i there are only two possibilities:
s[i + 2]is'#': the two digitss[i]s[i + 1]form a number from10to26, the letter'a' + number - 1. Skip all three characters.- Otherwise
s[i]alone is a digit from1to9, the letter'a' + digit - 1. Skip one character.
Looking ahead is what makes this unambiguous. In "1326#", reading 1 and 3 as single digits is correct only because no '#' follows two places later; at 2, the '#' two places ahead tells us that 26# is one letter, 'z'. Reading from the right also works (a '#' always closes a two-digit code), but scanning forward with the look-ahead is just as simple.
Complexity: O(n) time, and O(n) space for the answer.
class Solution:
def freqAlphabets(self, s: str) -> str:
out = []
i, n = 0, len(s)
while i < n:
if i + 2 < n and s[i + 2] == "#":
# Two digits and a '#': a letter from 'j' (10#) to 'z' (26#).
out.append(chr(ord("a") + int(s[i : i + 2]) - 1))
i += 3
else:
# A single digit: a letter from 'a' (1) to 'i' (9).
out.append(chr(ord("a") + int(s[i]) - 1))
i += 1
return "".join(out)