LeetCode 91. Decode Ways

原题链接在这里:https://leetcode.com/problems/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.

题解:

要求的是decode的方法. Let dp[i] denotes up to index i, the number of ways to decode it.

递推和等台阶的题目很像. 以"321" 为例,到了第三位时, s.substring(i-1, i) = "1"是 valid的, s.substring(i-2, i) = "21" 也是valid的.

dp[i] = dp[i-1] + dp[i-2]. 

答案是dp[n].

初始化用到前两个, 所以要有两个base case. dp[0] = 1. dp[1]看第一个字符是否是'0', 若不是, dp[0]=1.

Note: 0 非常烦人. 若是string 是"09","10",  对应的数字9, 10都在1到26之间,但“0”根本就不能decode, 所以任何包含 "0"的字符串都是非法的.

Time Complexity: O(n). Space: O(n). n = s.length().

AC Java:

 1 class Solution {
 2     public int numDecodings(String s) {
 3         if(s == null || s.length() == 0){
 4             return 1;
 5         }
 6         
 7         int n = s.length();
 8         
 9         int [] dp = new int[n+1];
10         dp[0] = 1;
11         for(int i = 0; i<n; i++){
12             char c = s.charAt(i);
13             if(c>='1' && c<='9'){
14                 dp[i+1] += dp[i];
15             }
16             
17             if(i>0){
18                 int val = Integer.valueOf(s.substring(i-1,i+1));
19                 if(val>=10 && val<=26){
20                     dp[i+1] += dp[i-1];
21                 }
22             }
23         }
24         
25         return dp[n];
26     }
27 }

只用到前面两个历史值. 可以降维处理.

Time Complexity: O(s.length()). Space: O(1).

AC Java:

 1 class Solution {
 2     public int numDecodings(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         
 7         int n = s.length();
 8         int first = 1;
 9         int second = s.charAt(0) == '0' ? 0 : 1;
10         for(int i = 1; i < n; i++){
11             char c = s.charAt(i);
12             int third = 0;
13             if(c >= '1' && c <= '9'){
14                 third += second;
15             }
16             
17             int val = Integer.valueOf(s.substring(i - 1, i + 1));
18             if(val >= 10 && val <= 26){
19                 third += first;
20             }
21             
22             first = second;
23             second = third;
24         }
25         
26         return second;
27     }
28 }

跟上Decode Ways II.

posted @ 2015-09-15 07:37  Dylan_Java_NYC  阅读(378)  评论(0编辑  收藏  举报