14 Decrypt String from Alphabet to Integer Mapping

关注 每天一道编程题 专栏,一起学习进步。

题目

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值