LeetCode 91 Decode Ways

本文介绍了解码数字字符串问题,给出了一种使用动态规划的方法来计算一个由数字组成的字符串有多少种不同的解码方式。通过两个核心条件限制解码的可能性,一是当前位数字不为0,二是前两位数字组合在10到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.

类似与爬楼梯的题目,number[i] = number[i-1] + number[i-2],但要加很多限制条件。
第一: s[i-1]不能是0,只有s[i-1]不是0,number[i]才能加上number[i-1]
第二,s[i-2,i]中获得的整数必须在10到26之间,number[i]才能加上number[i-2]

	public int numDecodings1(String s) {
		int n0 = 1;//前i-2位共有多少编码方式
		int n1 = 1;//前i-1位共有多少编码方式
		if (s.length() == 0 || s.charAt(0) == '0') return 0;
		for (int i = 2; i <= s.length(); i++) {
			int n = 0; //前i位共有多少个编码方式.
			if (s.charAt(i - 1) != '0') n = n1; //如果前一位不是0,+n1
			int num = Integer.parseInt(s.substring(i - 2, i));
			if (num >= 10 && num <= 26) n += n0;//如果前两位介于10到26,可以两位缩成1位编码,+n0即可.
			n0 = n1;
			n1 = n;
		}
		return n1;
	}
爬楼梯的连接 http://blog.youkuaiyun.com/niuooniuoo/article/details/50949415


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值