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.

链接: http://leetcode.com/problems/decode-ways/

6/4/2017

抄的答案

注意

1. 第3行第三个判断条件

2. 第12行用substring来求int

3. 分2种情况讨论答案,只有当前digit和包括之前digit的情况。然后更新dp

 1 public class Solution {
 2     public int numDecodings(String s) {
 3         if (s == null || s.equals("") || s.charAt(0) == '0') {
 4             return 0;
 5         }
 6         int[] dp = new int[s.length() + 1];
 7 
 8         dp[0] = 1;
 9         dp[1] = 1;
10 
11         for (int i = 2; i <= s.length(); i++) {
12             int number = Integer.parseInt(s.substring(i - 2, i));
13             int oneDigit = s.charAt(i - 1) == '0'? 0: dp[i - 1];
14             int twoDigits = (number < 10 || number > 26)? 0: dp[i - 2];
15             dp[i] = oneDigit + twoDigits;
16         }
17         return dp[s.length()];
18     }
19 }

也可以不用dp节省空间复杂度

更直观的做法

https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation

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

更多讨论:

https://discuss.leetcode.com/category/99/decode-ways

posted @ 2017-06-05 06:54  panini  阅读(166)  评论(0编辑  收藏  举报