首页 > 其他 > 详细

91. Decode Ways

时间:2017-06-05 09:32:31      阅读:259      评论:0      收藏:0      [点我收藏+]

题目:

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

原文:http://www.cnblogs.com/panini/p/6943180.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!