解码字母到整数映射

 

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

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;
    }
}

 

posted @ 2020-05-18 01:43  TinyMark  阅读(171)  评论(0编辑  收藏  举报