Decode Ways

来源:互联网 发布:复杂网络 什么专业 编辑:程序博客网 时间:2024/05/21 10:19

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.


参考了网上的解法,这里写一下总结的思路。

  1. 首先,使用一个数组保存当前的个数dp[i] 表示从头到当前i位一共有多少种解码方法。一共有两种情况需要考虑: 1。 如果i-1 i 位组合在一起能够组成一个字母(1~26),那么dp[i] += dp[i-2]; 2。 如果第i位!= 0, 那么在第i位可以自己解码,dp[i] += dp[i-1]。
  2. 如果当前值为0, 那么这个零可以跟前一位组合成的结果;如果当前组合值(i-1 i)超过26或者小于10,那么说明这一位不能够通过dp[i-2]得到,只能够解码当前的i位,所以dp[i] = dp[i-1]。
  3. 考虑到以上两种情况,还有特殊情况,这道题就可以做出来了。
public int numDecodeing(String s){    if(s == null || s.length == 0 ||(s.length ==1 && s.charAt(0)=='0')) return 0;    int [] result = new int[s.length+1];    result[0] = 1;//这里是为了当s[0]s[1]能够组合成一种编码情况的时候,result[2] = result[2-2] = result[0] = 1, 表示有一种解码方式    result[1] = s.charAt(0)=='0'?0:1;//1表示当前有一种解法,如果为零那么没有办法解码。    for(int i=2;i<=nums.length;i++){        int pre = nums.charAt(i-2)-'0';        int cur = nums.charAt(i-1)-'0';        int value = pre * 10 + cur;        if(value <= 26 && value >= 10){            result[i] += result[i-2];        }        if(cur!=0){            result[i] += result[i-1];        }    }    return result[result.length-1];}

写的时候有点崩,以后要注意啊

0 0
原创粉丝点击