leetcode菜鸡斗智斗勇系列(10)--- Decrypt String from Alphabet to Integer Mapping

1.原题:

https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/submissions/

 

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.

翻译:

给一个string s,由一串数组和‘#’组成,我们需要把其解码成英语小字母。

Input: s = "10#11#12"

Output: "jkab"

解释: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

 

2.解题思路:

这道题考验的是你对string,char的理解,其实用java写这个题很麻烦,因为Java的string类实在是很麻烦,但是我就当顺便练手了。实际上推荐用C类语言去弄,因为C的string本身就是char的array。。。(当然了你可以声明char array)

 

class Solution {
    public String freqAlphabets(String s) 
    {
        String res =""; //初始化一个string类
        for (int i = 0; i < s.length(); i++)
        {
            if ((i+2) < s.length() && s.charAt(i + 2) == '#')//向前搜索2个位置找#标志
            {
                String tmp_1 = String.valueOf(s.charAt(i))+ String.valueOf(s.charAt(i+1));
                int tmp_2 = Integer.parseInt(tmp_1);
                String tmp_3 = String.valueOf((char)('j' + tmp_2 - 10));
                res += tmp_3; //#的数字肯定是大于10的,而且是从j开始,如果是10的话,
                i += 2; //10-10=0,这时候就是J。如果是11, 11-10=1,为j之后的k。
            }
            else
            {
                char tmp_4 = (char)((s.charAt(i) - '1') + 'a');//从0开始为a,以此类推。
                String tmp_3 = String.valueOf(tmp_4);
                res += tmp_3;                
            }
        }
        return res;
    }
}

 

 

参考阅读:

1.Java 如何将String转化为Int:https://blog.csdn.net/a772304419/article/details/79723249

2.Java charAt() 方法:https://www.runoob.com/java/java-string-charat.html

3.Java中char和String的相互转换:https://www.cnblogs.com/rrttp/p/7922202.html

4.Char类型的加减法:https://blog.csdn.net/wz568780720/article/details/81612467

posted @ 2020-01-07 15:08  Parachute黑喵  阅读(235)  评论(0编辑  收藏  举报