[leetcode] Decode ways

本文解析了一道经典的算法题目——解码方式。这是一道动态规划问题,通过递推公式计算字符串的不同解码方法数量。文章提供了完整的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://leetcode.com/onlinejudge#question_91[/url]
Decode WaysJun 25 '121292 / 5011
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.


Solution: DP Problem again.


public class Solution {
public int numDecodings(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if(s.length() == 0) return 0;
int num[] = new int[s.length()];

int n1 = Integer.parseInt(s.substring(0,1));
if(n1==0) return 0;
if(s.length() == 1) return 1;
num[0]=1;

int n2 = Integer.parseInt(s.substring(0,2));
if(n2==10 || n2==20 || (n2>26 && n2%10!=0)) num[1] = 1;
else if(n2<=26 && n2>=11) num[1] = 2;
else return 0;

for(int i=2;i<s.length();i++){
n1 = Integer.parseInt(s.substring(i,i+1));
n2 = Integer.parseInt(s.substring(i-1,i+1));
if(n1==0 && n2==0) return 0;
if(n1 != 0) num[i] += num[i-1];
if(n2>=10 && n2 <= 26) num[i] += num[i-2];
}
return num[s.length() -1];
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值