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.

   题目大意:按照他的映射关系,给定的字符串有多少种解析的方法;

   思路 : 这道题,很像求某个集合的所有子集;

   比如说,求{1,2,3,4} 的子集,那么sub(4) = sub{3} + (sub{3}里面的每个子集都加4);

   而这里,s = "1254" , decode(1) = 1 decode(2) 可以在decode(1)的每种解析方法后+2 , 也可以和1组合   decode(2) = decode(1) + 1 ;

   decode(3) , 5 可以放入decode(2)中的任意解析方法,5也可以和组合,然后在放入decode(1)的任意方法中!

  所以 ,得到递归式:

  

decode(n) = decode(n - 1) + decode(n - 2)  n与n-1能组合且n != 0
decode(n) = decode(n - 2) n == 0 且 n 与 n-1能组合
decode(n) = decode(n - 1) n != 0 且n , n-1 不能组合
decode(n) = 0 n == 0 且 n , n - 1 不能组合

   这道题目,调了好久,细节问题!

public class Solution {
    public int numDecodings(String s) {
        int len = s.length();
        int[] conseq = new int[len + 1];
        
        if (len == 0) return 0;
        char ch = s.charAt(0);
        if (ch == '0') return 0;
        
        conseq[0] = 1;
        conseq[1] = 1;
        if (len < 2) return 1;
        
        for(int i = 2; i <= len ; i++) {
            // 如果取得当前字符=='0'而且还不能与前面那个元素组合的话,那么整个字符串不能decode
            if (s.charAt(i - 1) == '0' && !canCombination(s , i - 1) ) {
                conseq[len] = 0;
                break;
            }
            // 能与前面那个组合
            if (canCombination(s , i - 1)){
                // 如果他== 0 ,那么它就只能与前一个组合了,解码的方式只有 i- 2有关
                if (s.charAt(i - 1) == '0' )
                    conseq[i] = conseq[i - 2];
                else 
                //  != 0 ,那么它可以自己组合,也可以和前一个组合
                    conseq[i] = conseq[i - 1] + conseq[i - 2];
            } else {
                conseq[i] = conseq[i - 1];
            }
        }
        return conseq[len];
    }
    // 细节地方出错!!
    public boolean canCombination(String s , int idx) {
        int pre = Character.getNumericValue(s.charAt(idx - 1) );
        int cur = Character.getNumericValue(s.charAt(idx));
        if (pre <= 0 || pre > 2) return false;
        if (pre == 2) {
            if (cur > 6) return false;
            return true;
        }
        if (cur < 0) return false;
        return true;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值