Decrypt String from Alphabet to Integer Mapping
Problem
You are given a string s of digits and '#'. Map it to lowercase letters where '1'..'9' mean 'a'..'i' and '10#'..'26#' mean 'j'..'z'. Decode s by reading left to right: if the next two characters are followed by '#', take that two-digit code; otherwise take the single digit. Return the decoded string (the test guarantees a unique valid decoding).
s = "10#11#12""jkab"def freq_alphabets(s):
res = []
i = 0
while i < len(s):
if i + 2 < len(s) and s[i + 2] == "#":
num = int(s[i:i + 2])
i += 3
else:
num = int(s[i])
i += 1
res.append(chr(ord("a") + num - 1))
return "".join(res)
function freqAlphabets(s) {
let res = "";
let i = 0;
while (i < s.length) {
let num;
if (i + 2 < s.length && s[i + 2] === "#") {
num = parseInt(s.slice(i, i + 2), 10);
i += 3;
} else {
num = parseInt(s[i], 10);
i += 1;
}
res += String.fromCharCode(96 + num);
}
return res;
}
class Solution {
public String freqAlphabets(String s) {
StringBuilder res = new StringBuilder();
int i = 0;
while (i < s.length()) {
int num;
if (i + 2 < s.length() && s.charAt(i + 2) == '#') {
num = Integer.parseInt(s.substring(i, i + 2));
i += 3;
} else {
num = s.charAt(i) - '0';
i += 1;
}
res.append((char) ('a' + num - 1));
}
return res.toString();
}
}
string freqAlphabets(string s) {
string res = "";
int i = 0, n = s.size();
while (i < n) {
int num;
if (i + 2 < n && s[i + 2] == '#') {
num = (s[i] - '0') * 10 + (s[i + 1] - '0');
i += 3;
} else {
num = s[i] - '0';
i += 1;
}
res += (char) ('a' + num - 1);
}
return res;
}
Explanation
The encoding is ambiguous only if you read it backwards — the '#' is the disambiguator, and it always trails a two-digit code. So the cleanest decode walks left to right with a manual cursor and peeks ahead for a '#'.
At position i, we look two slots ahead. If s[i+2] is '#', then s[i] and s[i+1] form a number in 10..26, and we advance the cursor by 3 to skip the hash too.
Otherwise the single digit s[i] is a code in 1..9, and we advance by 1. Either way we now have an integer num in 1..26.
We turn it into a letter with offset arithmetic: 'a' + num - 1, so 1 maps to 'a' and 26 to 'z'. Appending each letter as we go rebuilds the message. A plain while loop (not for) is essential because each step advances the cursor by a variable amount.
Example: "10#11#12". "10#"→10→j, "11#"→11→k, then "1"→a, "2"→b, giving "jkab".