You are given a string s
formed by digits and '#'
. We want to map s
to English lowercase characters as follows:
'a'
to 'i'
) are represented by ('1'
to '9'
) respectively.'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 <= 1000
s
consists of digits and the '#'
letter.s
will be a valid string such that mapping is always possible.The problem asks to decrypt a string s
where digits map to lowercase letters. Digits '1' to '9' map to 'a' to 'i', respectively. Two-digit numbers followed by '#' map to 'j' to 'z'. The function should return the decrypted string.
The most straightforward approach is to simulate the decryption process. We iterate through the string:
We build the decrypted string character by character and return it.
class Solution:
def freqAlphabets(self, s: str) -> str:
res = ""
i = 0
n = len(s)
while i < n:
if i + 2 < n and s[i+2] == '#':
num = int(s[i:i+2])
res += chr(ord('a') + num - 1)
i += 3
else:
num = int(s[i])
res += chr(ord('a') + num - 1)
i += 1
return res
s
. We iterate through the string once.res
can be at most the same length as the input string.The solution can be easily adapted to other programming languages using similar logic. The core idea remains the same: iterate through the string, check for the '#' character to handle two-digit mappings, and build the resulting string.
(Java)
class Solution {
public String freqAlphabets(String s) {
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
if (i + 2 < s.length() && s.charAt(i + 2) == '#') {
int num = Integer.parseInt(s.substring(i, i + 2));
sb.append((char) (num + 96)); // 'a' is 97 in ASCII
i += 3;
} else {
int num = Integer.parseInt(s.substring(i, i + 1));
sb.append((char) (num + 96));
i++;
}
}
return sb.toString();
}
}
(C++)
string freqAlphabets(string s) {
string res = "";
for (int i = 0; i < s.length(); ++i) {
if (i + 2 < s.length() && s[i + 2] == '#') {
int num = stoi(s.substr(i, 2));
res += (char)('a' + num - 1);
i += 2;
} else {
int num = s[i] - '0';
res += (char)('a' + num - 1);
}
}
return res;
}
The other languages (JavaScript, Go, C#, etc.) would follow a similar pattern, adapting the string manipulation and character conversion functions appropriately.