5303. 解码字母到整数映射----------LeetCode

解题思路:

(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();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值