1309. Decrypt String From Alphabet to Integer Mapping

1309. Decrypt String from Alphabet to Integer Mapping #

题目 #

  • 给你一个字符串 s,它由数字('0' - '9')和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符:
    • 字符('a' - 'i')分别用('1' - '9')表示。
    • 字符('j' - 'z')分别用('10#' - '26#')表示。
  • 返回映射之后形成的新字符串。
  • 题目数据保证映射始终唯一。

思路 #

模拟 #

代码 #

模拟 #

class Solution {
    public String mapping(String s) {
        switch (s) {
            case "1": return "a";
            case "2": return "b";
            case "3": return "c";
            case "4": return "d";
            case "5": return "e";
            case "6": return "f";
            case "7": return "g";
            case "8": return "h";
            case "9": return "i";
            case "10#": return "j";
            case "11#": return "k";
            case "12#": return "l";
            case "13#": return "m";
            case "14#": return "n";
            case "15#": return "o";
            case "16#": return "p";
            case "17#": return "q";
            case "18#": return "r";
            case "19#": return "s";
            case "20#": return "t";
            case "21#": return "u";
            case "22#": return "v";
            case "23#": return "w";
            case "24#": return "x";
            case "25#": return "y";
            case "26#": return "z";
        }
        return "";
    }

    public String freqAlphabets(String s) {
        String ans = "";
        for (int i = 0; i < s.length(); ) {
            if (i+2<s.length() && s.charAt(i+2) == '#') {
                ans += mapping(s.substring(i, i+3));
                i += 3;
            }
            else {
                ans += mapping(s.substring(i, i+1));
                i += 1;
            }
        }
        return ans;
    }
}