leetCode 91.Decode Ways (解码方式) 解题思路和方法

来源:互联网 发布:admaster数据分析 编辑:程序博客网 时间:2024/06/05 16:27

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.

思路:本题用递归没有实现,可能是递归没有写好,最后在网上参考了资料写了动态规划的代码。

思想是判断当前判断当前值是否为0,不为0则f[i] = f[i] + f[i-1];

然后当前值和上一个字符能否组成26以下的输,能这与f[i] = f[i] + f[i-2]。

具体代码如下:

public class Solution {    public int numDecodings(String s) {    //动态规划标记    int[] f = new int[s.length()];    char[] c = s.toCharArray();    //边界情况    if(c.length == 0){    return 0;    }    //第一个元素    f[0] = c[0] > '0' ? 1:0;        if(c.length == 1){    return f[0];    }    //f[1]的值是关键,写不好,将会出现各种错误    int k = c[0] > '0' && c[1] > '0'? 1:0;    f[1] = k + (c[0] == '1' || c[0] == '2' && c[1] <= '6' ? 1:0);        //从前往后遍历    for(int i = 2; i < c.length; i++){    if(c[i] > '0'){//第一个元素大于0,添加情况    f[i] += f[i-1];    }    //在10-26之间则添加两个字母组成一个的情况    if(c[i-1] == '1' || (c[i-1] == '2' && c[i] <= '6')){    f[i] += f[i-2];    }    }        return f[c.length-1];    }}



0 0