zoukankan      html  css  js  c++  java
  • 解码字母到整数映射

    这个没啥好分析的!我的笨代码如下:

    class Solution {
        public String freqAlphabets(String s) {
            int i = 0;
            int j = 0;
            char[] str=s.toCharArray();
            String result="";
            for(i=0;i<str.length;i++){
                j=i;
                int first = Integer.parseInt(String.valueOf(str[j]));
    //            j+1和j+2均不能越界
                if (j+1<str.length && j+2<str.length && str[j+2]=='#'){ //满足第三位是#
                    int second = Integer.parseInt(String.valueOf(str[j+1]));
                    if ((first*10+second)>=10 && (first*10+second)<=26){
    //                    满足两位数转换,十分位的数字乘以10
    // ASCII码表中 48-57 为十进制数字0-9 ,65-90 为 A-Z ,97-122 为 a-z
                        result = result+ (char)(96+first*10+second);
                        i = i+2;//因为到循环框时,又要对i+1,故此处为i+2
                    }
                }else {
                    result = result + (char)(96+first);
                }
            }
            return result;
        }
    }

    高手代码(逆向思维,倒序遍历,用的是C#):

    public class Solution {
        public string FreqAlphabets(string s)
        {
            string res = "";
            for (int i = s.Length-1; i >=0; i--)
            {
                int cur = 0;
                if (s[i]=='#')
                {
                    cur = (s[i - 2] - '0') * 10 + s[i - 1] - '0';
                    i -= 2;
                }
                else
                {
                    cur = s[i] - '0';
                }
                char c = (char)(cur-1 +Convert.ToInt32('a'));
                res = c+res;
            }
    
            return res;
        }
    }
  • 相关阅读:
    input file 上传图片并显示
    关于npm ---- npm 命令行运行多个命令
    webpack4.x 配置
    React的生命周期
    HTML5 meta 属性整理
    css 命名规范
    html5 标签 meter 和 progress
    .NET Linq TO XML 操作XML
    .NET 字符串指定规则添加换行
    Linux Centos上部署ASP.NET网站
  • 原文地址:https://www.cnblogs.com/Mark-blog/p/12908023.html
Copyright © 2011-2022 走看看