解题思路:
(1)将字符和字符对应的映射用hashmap存起来
(2)倒序遍历字符串,如果当前字符是“#”,则连着遍历三个字符,将是哪个字符拼接起来,从map中找到其对应的映射
如果不是“#”,则直接从map中找其对应的映射。把每次找到的映射用StringBuilder拼接起来
(3)将(2)中得到的StringBuilder通过reverse()倒序输出,并转换成String返回
代码实现如下:
class Solution {
public String freqAlphabets(String s) {
Map<String,String> maps=new HashMap<String,String>();
maps.put("1","a");
maps.put("2","b");
maps.put("3","c");
maps.put("4","d");
maps.put("5","e");
maps.put("6","f");
maps.put("7","g");
maps.put("8","h");
maps.put("9","i");
maps.put("10#","j");
maps.put("11#","k");
maps.put("12#","l");
maps.put("13#","m");
maps.put("14#","n");
maps.put("15#","o");
maps.put("16#","p");
maps.put("17#","q");
maps.put("18#","r");
maps.put("19#","s");
maps.put("20#","t");
maps.put("21#","u");
maps.put("22#","v");
maps.put("23#","w");
maps.put("24#","x");
maps.put("25#","y");
maps.put("26#","z");
StringBuilder res=new StringBuilder();
int len=s.length();
int j=0;
for(int i=len-1;i>=0;i-=j){
if(s.charAt(i)=='#'){
if(i>=2){
String temp=s.substring(i-2,i+1);
res.append(maps.get(temp));
}
j=3;
}
else{
String temp=s.substring(i,i+1);
res.append(maps.get(temp));
j=1;
}
}
return res.reverse().toString();
}
}