首页 > 代码库 > 【leetcode刷题笔记】Decode Ways

【leetcode刷题笔记】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.


 

题解:DP问题。

对于s中位置i(s[i] != ‘0‘)上的字符,有两种可能:

  1. 直接把i译码成对应的字母,那么此时有dp[i-1]中方法;
  2. 如果i和i-1上的字符可以共同组成一个字母(s(i-1,i)在[10,26]范围中),那么又有dp[i-2]种译码方法,所以此时dp[i] = dp[i-1]+dp[i-2];

代码如下:

 1 public class Solution { 2     private boolean isValidNum(String s,int i){ 3         if(i <= 0) 4             return false; 5         int first = s.charAt(i-1)-‘0‘; 6         int second = s.charAt(i)-‘0‘; 7         int num = first*10 + second; 8         if(num >= 10 && num <= 26) 9             return true;10         return false;11     }12     public int numDecodings(String s) {13         if(s==null || s.length() == 0)14             return 0;15         int length = s.length();16         int[] dp = new int[length+1];17         18         dp[0] = 1;19         dp[1] = s.charAt(0) == ‘0‘?0:1;20         21         for(int i=2;i<=length;i++){22             if(s.charAt(i-1) != ‘0‘)23                 dp[i]=dp[i-1];24             25             if(isValidNum(s, i-1))26                 dp[i] += dp[i-2];27         }28         return dp[length];        29     }30 }