码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 91. Decode Ways 解码方法

时间:2018-02-28 16:26:42      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:length   map   new   its   min   []   letter   xrange   ber   

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.

思路:

用动态规划Dynamci Programming来解。一位数时不能为0,两位数不能大于26,其十位上的数也不能为0。用哈希表来存或者用两个变量来存。

State: dp[i]

Function: dp[i] = dp[i - 1] (if i - 1 != 0) + dp[i - 2] (if i - 2 == 1 or i - 2 == 2 and i -1 < = 6)

Initialize: dp[0] = 0, dp[1] = 1

Return: dp[n]

Java 1:

public class Solution {
    public int numDecodings(String s) {
        if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == ‘0‘)) return 0;
        int[] dp = new int[s.length() + 1];
        dp[0] = 1;
        for (int i = 1; i < dp.length; ++i) {
            dp[i] = (s.charAt(i - 1) == ‘0‘) ? 0 : dp[i - 1];
            if (i > 1 && (s.charAt(i - 2) == ‘1‘ || (s.charAt(i - 2) == ‘2‘ && s.charAt(i - 1) <= ‘6‘))) {
                dp[i] += dp[i - 2];
            }
        }
        return dp[s.length()];
    }
}

Java 2:

public class Solution {
    public int numDecodings(String s) {
        if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == ‘0‘)) return 0;
        int prev = 1, prev_prev = 0;
        for (int i = 0; i < s.length(); i++) {
            int cur = 0;
            if (s.charAt(i) != ‘0‘) {
                cur = prev;
            }
            if (i > 0 && (s.charAt(i - 1) == ‘1‘ || (s.charAt(i - 1) == ‘2‘ && s.charAt(i - 1) <= ‘6‘))) {
                cur += prev_prev;
            }
            prev_prev = prev;
            prev = cur;
        }
        return prev;
    }
}

  

Python:

class Solution(object):
    def numDecodings(self, s):
        if len(s) == 0 or s[0] == ‘0‘:
            return 0
        prev, prev_prev = 1, 0
        for i in xrange(len(s)):
            cur = 0
            if s[i] != ‘0‘:
                cur = prev
            if i > 0 and (s[i - 1] == ‘1‘ or (s[i - 1] == ‘2‘ and s[i] <= ‘6‘)):
                cur += prev_prev
            prev, prev_prev = cur, prev
        return prev

  

  

[LeetCode] 91. Decode Ways 解码方法

标签:length   map   new   its   min   []   letter   xrange   ber   

原文地址:https://www.cnblogs.com/lightwindy/p/8483755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!