Decode Ways

 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.

 

基本上一涉及组合可能性有多少种,就必须是dp, 跟爬楼梯很像

一开始想的错了,比如1217,12后面可能是1,7也可能是17,所以不是线性相加 1+ 1(12)+(21)+(17)而是乘积

此外有些特殊情况也可以通过dp来规避,比如出现10,01,100,00

注意ref中的 s=="0"不对,必须用string.equals("")

public class Solution {
    public int numDecodings(String s) {
        if(s==null||s.length()==0||s.charAt(0)=='0') return 0;
        int[] dp = new int[s.length()+1];
        dp[0]=1;
        if(isV(s.substring(0,1)))
            dp[1]=1;
        for(int i=2;i<=s.length();i++){
            if(isV(s.substring(i-1,i))){
                dp[i] += dp[i-1];
            }
            if(isV(s.substring(i-2,i))){
                dp[i] += dp[i-2];
            }
        }
        return dp[s.length()];
    }
    private boolean isV(String t){
        if(t==null||t.length()==0||t.charAt(0)=='0')
            return false;
        int code = Integer.parseInt(t);
        return (code>=1 && code<=26);
    }
}

 

posted @ 2015-06-09 07:54  世界到处都是小星星  阅读(116)  评论(0编辑  收藏  举报