LeetCode:Decode Ways 解题报告

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.

SOLUTION 1:

我们使用DP来处理这个题目。算是比较简单基础的一维DP啦。

1. D[i] 表示前i个字符能解的方法。

2. D[i] 有2种解法:

 1). 最后一个字符单独解码。 如果可以解码,则解法中可以加上D[i - 1]

 2). 最后一个字符与上一个字符一起解码。 如果可以解码,则解法中可以加上D[i - 2]

 以上2种分别判断一下1个,或是2个是不是合法的解码即可。

 1 public class Solution {
 2     public int numDecodings(String s) {
 3         if (s == null || s.length() == 0) {
 4             return 0;
 5         }
 6         
 7         int len = s.length();
 8         
 9         // D[i] 表示含有i个字符的子串的DECODE WAYS.
10         int[] D = new int[len + 1];
11         
12         D[0] = 1;
13         
14         for (int i = 1; i <= len; i++) {
15             D[i] = 0;
16             
17             // 现在正在考察的字符的索引.
18             int index = i - 1;
19             // 最后一个字符独立解码
20             if (isValidSingle(s.charAt(index))) {
21                 D[i] += D[i - 1];
22             }
23             
24             // 最后一个字符与上一个字符一起解码
25             if (i > 1 && isValidTwo(s.substring(index - 1, index + 1))) {
26                 D[i] += D[i - 2];
27             }
28         }
29         
30         return D[len];
31     }
32     
33     public boolean isValidSingle(char c) {
34         if (c >= '1' && c <= '9') {
35             return true;
36         }
37         
38         return false;
39     }
40     
41     public boolean isValidTwo(String s) {
42         int num = Integer.parseInt(s);
43         
44         return (num >= 10 && num <= 26);
45     }
46 }
View Code

 2015.1.3 redo:

public class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int len = s.length();
        
        // The result of first i digits.
        int[] D = new int[len + 1];
        
        for (int i = 0; i <= len; i++) {
            if (i == 0) {
                D[i] = 1;
            } else {
                // i >= 1
                D[i] = 0;
                if (i >= 2 && isValid(s.substring(i - 2, i))) {
                    D[i] += D[i - 2]; 
                }
                
                // The digit should not be 0.
                if (s.charAt(i - 1) != '0') {
                    D[i] += D[i - 1]; 
                }
            }
        }
        
        return D[len];
    }
    
    public boolean isValid(String s) {
        int num = Integer.parseInt(s);
        
        return num >= 10 && num <= 26;
    }
}
View Code

 

SOLUTION 2:

http://www.ninechapter.com/solutions/

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/NumDecodings.java

posted on 2014-11-22 18:34  Yu's Garden  阅读(907)  评论(0编辑  收藏  举报

导航