zoukankan      html  css  js  c++  java
  • 1309. 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.
    class Solution {
        public String freqAlphabets(String s) {
            StringBuilder sb = new StringBuilder();
            if(s.length() == 0 || s == null || s.charAt(0) == '#') return "";
            for(int i = 0; i < s.length(); i++){
                if((i+2) < s.length() && s.charAt(i+2) == '#'){
                    sb.append((char) ('a' + Integer.parseInt(s.substring(i, i+2)) - 1));
                    i += 2;
                }
                else{
                    sb.append((char) ('a' + Integer.parseInt(s.substring(i, i+1)) - 1));
                }
            }
            return sb.toString();
        }
    }

    可以直接做,先判断第三位是不是#,如果是就append前两位数对应的字母,记得要i = i + 2,总共应该是个+3跳过整个字母的对应,因为for循环中还有个+1所以这里+2就好了

    如果第三位不是#,就说明是10位一下,方法照做就好,最后从头+1跳过就可以。

    StringBuilder比String要好

  • 相关阅读:
    CD4051
    sbit和sfr的定义
    EEPROM与FLASH的区别
    九LWIP学习笔记之最后的战役
    八LWIP学习笔记之用户编程接口(NETCONN)
    七LWIP学习笔记之传输控制协议(TCP)
    六LWIP学习笔记之用户数据报协议(UDP)
    java实现二叉查找树
    线程的锁对象
    MAP
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12169408.html
Copyright © 2011-2022 走看看