关注 每天一道编程题 专栏,一起学习进步。
题目
Given a string s formed by digits (‘0’ - ‘9’) 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.
It’s guaranteed 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”
Example 3:
Input: s = “25#”
Output: “y”
Example 4:
Input: s = “12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#”
Output: “abcdefghijklmnopqrstuvwxyz”
Constraints:
1 <= s.length <= 1000
s[i] only contains digits letters ('0'-'9') and '#' letter.
s will be valid string such that mapping is always possible.
分析
题意:a~i用0~9表示,j~z用10#~26#表示
给一个数字和#组成字符串,将其解密为字母
可以转化为ASCII码,0与a相差96,因此数字与对应字母都相差96
难点:
0~9和10#~26#编码不统一,没有整体都用#分割
思路:从前向后匹配,如果第三个字符为’#’,则往后跳3个字符,
解答
class Solution {
public String freqAlphabets(String s) {
int n = s.length();
String ans = "";
for(int i = 0; i < n; ) {
//由于i=i+3,因此最后两个需要略过,不然越界,因此i<n-2
if(i < n - 2 && s.charAt(i + 2) == '#') {
//拿到当前数字,substring取头不取尾
int num = Integer.parseInt(s.substring(i, i + 2));
ans += (char)(num + 96);
//往后跳跃3个字符
i = i + 3;
continue;
}
//如果不是#,则直接加上
ans += (char)(97 + s.charAt(i) - '1');
i++;
}
return ans;
}
}