LeetCode之计算解密的数量DecodeWays

来源:互联网 发布:郝斌c语言不压缩百度云 编辑:程序博客网 时间:2024/05/01 13:13

问题描述:

/** * A message containing letters from A-Z is being encoded to numbers using the * following mapping: *  * 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, * determine the total number of ways to decode it. *  * For example, Given encoded message "12", it could be decoded as "AB" (1 2) or * "L" (12). *  * The number of ways decoding "12" is 2. */

在加密中用‘A’来加密为’1’,’B’加密为’2’.但是在解密时,’12’可能被 解密为’AB’(1,2),也可能被解密为’L’(12)。所以给你一串加密后的数字串,问你有多少种解密的方式。
定义数组C[s.length()+1],C[i+1]表示为:到s[0….i]有C[i+1]种解密的方法。
而且有几个限制的条件:
1、s[i-1]不能等于0,若为0,则C[i]=C[i-2];
2、s[i-1,i-2]的数字只能为1~26之间。
例如:
1010,生成的C数组为:[1,1,1,1,1]
10000,生成的C数组为:[1,1,1,0,0,0,0,0,0]
代码如下:

public static int numDecodings(String s){        if(s.length()==0)            return 0;        int[]c=new int[s.length()+1];        c[0]=1;        if(s.charAt(0)!='0')            c[1]=c[0];        else            c[1]=0;        for(int i=2;i<=s.length();i++)        {            if(s.charAt(i-1)=='0')            {                c[i]=0;            }else{                c[i]=c[i-1];            }            if(s.charAt(i-2)=='1'||s.charAt(i-2)=='2'&&s.charAt(i-1)<='6')            {                c[i]+=c[i-2];            }        }        return c[s.length()];    }
0 0
原创粉丝点击