We can decode the string by scanning from right to left. If we see a ‘#’, we know the previous two digits form a number from 10 to 26, mapping to ‘j’ to ‘z’. Otherwise, each single digit maps to ‘a’ to ‘i’.
classSolution {
public: string freqAlphabets(string s) {
string ans;
int i = s.size() -1;
while (i >=0) {
if (s[i] =='#') {
int num = (s[i-2] -'0') *10+ (s[i-1] -'0');
ans += (char)('a'+ num -1);
i -=3;
} else {
ans += (char)('a'+ (s[i] -'0') -1);
i--;
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};
classSolution {
public String freqAlphabets(String s) {
StringBuilder ans =new StringBuilder();
int i = s.length() - 1;
while (i >= 0) {
if (s.charAt(i) =='#') {
int num = (s.charAt(i-2) -'0') * 10 + (s.charAt(i-1) -'0');
ans.append((char)('a'+ num - 1));
i -= 3;
} else {
ans.append((char)('a'+ (s.charAt(i) -'0') - 1));
i--;
}
}
return ans.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funfreqAlphabets(s: String): String {
val ans = StringBuilder()
var i = s.length - 1while (i >=0) {
if (s[i] =='#') {
val num = (s[i-2] - '0') * 10 + (s[i-1] - '0')
ans.append('a' + num - 1)
i -=3 } else {
ans.append('a' + (s[i] - '0') - 1)
i-- }
}
return ans.reverse().toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deffreqAlphabets(self, s: str) -> str:
ans: list[str] = []
i: int = len(s) -1while i >=0:
if s[i] =='#':
num = int(s[i-2:i])
ans.append(chr(ord('a') + num -1))
i -=3else:
ans.append(chr(ord('a') + int(s[i]) -1))
i -=1return''.join(ans[::-1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnfreq_alphabets(s: String) -> String {
let bytes = s.as_bytes();
letmut ans = Vec::with_capacity(bytes.len());
letmut i = bytes.len() asi32-1;
while i >=0 {
if bytes[i asusize] ==b'#' {
let num = (bytes[(i-2) asusize] -b'0') *10+ (bytes[(i-1) asusize] -b'0');
ans.push((b'a'+ num -1) aschar);
i -=3;
} else {
ans.push((b'a'+ (bytes[i asusize] -b'0') -1) aschar);
i -=1;
}
}
ans.reverse();
ans.into_iter().collect()
}
}