[leetcode] 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.

https://oj.leetcode.com/problems/decode-ways/

 

思路1:dfs。

思路2:dp。类似斐波那契数列,dp[i]表示从头到i位共有多少中组合。

  如果i-1位不等于0,则dp[i]需要加上dp[i-1]的情况。

  如果i-2位到i-1位在1-26之间,则dp[i]需要加上dp[i-2]情况。

 

public class Solution {
    // be careful of "0" "01" "100"
    public int numDecodings(String s) {
        if (s.length() == 0)
            return 0;

        int[] dp = new int[s.length() + 1];
        dp[0] = 1;
        if (s.charAt(0) != '0')
            dp[1] = 1;
        else
            dp[1] = 0;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) != '0')
                dp[i + 1] = dp[i];
            if (s.charAt(i - 1) != '0' && Integer.parseInt(s.substring(i - 1, i + 1)) <= 26)
                dp[i + 1] += dp[i - 1];

        }
        return dp[s.length()];

    }


    public static void main(String[] args) {
        String s = "1010";
        System.out.println(new Solution().numDecodings(s));
    }

}
View Code

 

第二遍记录: 类似斐波那契,当前位的种类数,取决于上一位的数量和上上位的数量,注意0和大于26的情况。

 

第三遍记录:此题比较坑的就是含有0的情况,不保证一定是可decode的,有可能返回是0,空字符串返回0。

 

 

public class Solution {
    //be careful of "0" "01" "100" 
    public int numDecodings(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int n = s.length();

        int[] dp = new int[n + 1];
        dp[0] = 1;
        if (s.charAt(0) != '0')
            dp[1] = 1;
        else
            dp[1] = 0;

        for (int i = 2; i <= n; i++) {
            int cur = s.charAt(i - 1) - '0';
            int pre = s.charAt(i - 2) - '0';
            if (cur != 0)
                dp[i] += dp[i - 1];
            if (pre != 0 && (pre < 2 || pre == 2 && cur <= 6))
                dp[i] += dp[i - 2];
        }

        return dp[n];

    }
}

 

 

 

参考:

http://blog.csdn.net/u011095253/article/details/9248109

http://blog.csdn.net/worldwindjp/article/details/19938131

 

posted @ 2014-07-01 23:44  jdflyfly  阅读(169)  评论(0编辑  收藏  举报