LeetCode 91 Decode Ways

LeetCode 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.

又是一道可以回溯或是dp的題目,一開始按照回溯的思路,每次判斷當前index的個位數與index,index+1對應的兩位數,查看兩種情況是否滿足decode要求,即個位數在1-9之間,兩位數在1-26之間。寫完了以后LTE了。。。

寫了1個半小時才改對dp的版本。。。真是無語了。。。
注意初始條件:

  1. 當長度小于什么時,應該直接返回?
  2. 應該初始化dp[0]和dp[1]嗎?分別初始化成什么?
  3. 寫出遞推公式
    這里有一個誤區,真正的判斷條件應該是:
    個位數在1-9之間,兩位數在10-26之間!??!

代碼:

public class Solution {
    public int numDecodings(String s) {
        int n = s.length();
        if (n <= 0) return 0;
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = (s.charAt(0) == '0') ? 0 : 1;
        
        for (int i = 2; i <= n; i++) {
            int first = Integer.valueOf(s.substring(i-1,i));
            int second = Integer.valueOf(s.substring(i-2,i));
            
            if (first >= 1 && first <= 9) 
                dp[i] += dp[i-1];
            if (second >= 10 && second <= 26)
                dp[i] += dp[i-2];
        }
        
        return dp[n];
    }
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容