Decrypt String from Alphabet to Integer Mapping
This can be solved by iterating the input string from right to left. If we encounter a ‘#’, it means the last two digits before ‘#’ represents a character from ‘j’ to ‘z’. If there’s no ‘#’, then the digit represents a character from ‘a’ to ‘i’.
Python solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| class Solution:
def freqAlphabets(self, s: str) -> str:
i = len(s) - 1
result = []
while i >= 0:
if s[i] == '#':
# Extract the two digits before '#'
num = int(s[i-2:i])
# Map the number to its corresponding character and append to the result
result.append(chr(ord('j') + num - 10)) # 'j' corresponds to 10
i -= 3
else:
# Map the single digit number to its corresponding character
result.append(chr(ord('a') + int(s[i]) - 1)) # 'a' corresponds to 1
i -= 1
# Since we processed the string from right to left, we need to reverse the result to get the correct order
return ''.join(result[::-1])
|
In this code:
- We initialize an index
i
to the end of the string and an empty list result
to store the characters. - We iterate over the string from the end to the start. If the current character is ‘#’, we get the previous two digits and map it to a character from ‘j’ to ‘z’. We then decrease the index by 3 to skip the processed digits and the ‘#’.
- If the current character is not ‘#’, it’s a single digit, which we map to a character from ‘a’ to ‘i’. We then decrease the index by 1.
- After processing the entire string, we join the characters in
result
into a string. We also reverse the string as we initially processed the characters from right to left. - Finally, we return the resulting string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Solution:
def freqAlphabets(self, s: str) -> str:
i = len(s) - 1
result = []
while i >= 0:
if s[i] == '#':
num = int(s[i-2:i])
char = chr(ord('j') + num - 10)
result.append(char)
i -= 3
else:
num = int(s[i])
char = chr(ord('a') + num - 1)
result.append(char)
i -= 1
result_reversed = result[::-1]
result_str = ''.join(result_reversed)
return result_str
|