1. 程式人生 > >91. Decode Ways

91. Decode Ways

char lean ive ger val n+1 pin category 更多

題目:

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

91. Decode Ways