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

1.原题:

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

 

Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:java

  • 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.git

It's guaranteed that a unique mapping will always exist.数组

翻译:app

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

Input: s = "10#11#12" .net

Output: "jkab" 翻译

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

 

2.解题思路:

这道题考验的是你对string,char的理解,其实用java写这个题很麻烦,由于Java的string类实在是很麻烦,可是我就当顺便练手了。实际上推荐用C类语言去弄,由于C的string自己就是char的array。。。(固然了你能够声明char array)orm

 

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:http://www.javashuo.com/article/p-abwvlqce-o.html

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

3.Java中char和String的相互转换:http://www.javashuo.com/article/p-pjlxghsu-mu.html

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

相关文章
相关标签/搜索