91. Decode Ways 解码方法
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,否则为1,也就是说如果字符串以0开头则这个0不会对应任何一个字母,在进行解码的时候必须跳过这个数字,接下来循环到第位,如果前一位数字处于1到9之间,则dp[i] = dp[i-1],
class Solution { public int numDecodings(String s) { int length = s.length(); int[] dp = new int[length+1]; dp[0] = 1; dp[1] = s.charAt(0)!='0' ? 1:0; for(int i =2;i<=length;i++){ int first = Integer.valueOf(s.substring(i-1,i)); int second = Integer.valueOf(s.substring(i-2,i)); System.out.println(first); System.out.println(second); if(0<first&&first<=9) dp[i] = dp[i-1]; if(10<=second&&second<=26) dp[i] = dp[i]+dp[i-2]; } System.out.println(Arrays.toString(dp)); return dp[length]; } }