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.

Show Tags

Have you met this question in a real interview?

思路: 用 dp 来存储 ways, 如果 为 0  , 就断开 ,设置成 0 , 每次 ways[i] =  ways[ i - 1] , 然后加上 如果前两位能和成 一个合法数字的,

思路 2: space o(1) 解法, 其实就是只利用 奇偶位的交叉相加。 & 1 其实就是 %2 一样。

易错点 : 主要要检查前两位, 所以要把 i = 0 单独算。  注意要  ways[i] +=  ways [i - 2];

注意两种解法的 起始点的设置 和 test case : 110 的情况。

public class Solution {
    public int numDecodings(String s) {
        int len = s.length();
        if(len < 1)
            return 0;
        int[] ways = new int[len + 1];
        ways[0] = 1;
        if(s.charAt(0) == '0'){//----因为下面要检查前两位
            ways[1] = 0;
        }else{
            ways[1] = ways[0];
        }
        for(int i = 2; i <= len; i++){
            if(s.charAt(i - 1) == '0'){
                ways[i] = 0;
            }else{
                ways[i] = ways[i - 1];
            }
            if(s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6')){//---
                ways[i] += ways[i - 2];// ---- 记住是 i - 2
            }
        }
        return ways[len];
	}
}

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值