Leetcode-Decode Ways

消息解码算法
本文介绍了一种使用动态规划解决消息解码问题的方法。对于由数字组成的编码消息,根据A到Z字母与1到26数字的对应关系进行解码。通过动态规划计算不同解码方式的数量,特别注意有效数字范围及特殊情况。

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.

Analysis:

This is a DP problem. d[i] is the number of ways to decode the first i chars.

d[i]=d[i-2]+d[i-1] if num(i-1,i) is a valid number and num(i,i) is a valid number.

NOTE: for a string with 2 chars, the number should be between 10 and 26. For a string with 1 char, the valid number should between 1 and 9. "0","01","02"...like this are all invalid.

Solution:

 1 public class Solution {
 2     public int numDecodings(String s) {
 3         if (s.length()==0) return 0;
 4         int[] d = new int[s.length()+1];
 5         d[0]=1;
 6         for (int i=1;i<d.length;i++){
 7             d[i]=0;
 8             int start = 0;
 9             if (i-2>start) start = i-2;
10             for (int k=start;k<i;k++){
11                String temp = s.substring(k,i);
12                if (temp.length()==1&&!temp.equals("0"))
13                    d[i]+=d[k];
14                if (temp.length()==2){
15                    int num = Integer.parseInt(temp);
16                    if (num<=26 && num>=10)
17                        d[i]+=d[k];
18                }
19             }
20          }
21          return d[s.length()];      
22     }
23 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4098786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值