LeetCode 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.

 

求不同的解码方法。

一般情况:

到位置n时的解的个数s[n]=s[n-1]+s[n-2];

特殊情况:

1、出现00,30,40……无解;

2、出现10,20:s[n]=s[n-2];

3、其它的值大于26的情况:s[n]=s[n-1];

 

代码:

class Solution {
public:
    int numDecodings(string s) {
        int len=s.size();
		if(len==0)	//数字串为空
			return 0;
		else if(len==1)	//仅有1个数字
			return s[0]!='0';
		int num[3];	//代表到前2个的解,到前1个的解,到当前位置的解。比用长串节省一些空间。
		if(s[0]=='0')	//第0个是'0'
			return 0;
		num[0]=1;num[1]=1;num[2]=1;
		for(int i=1;i<len;i++)
		{
			num[0]=num[1];num[1]=num[2];	//数据左移
			if(s[i]=='0'&&(s[i-1]>'2'||s[i-1]=='0'))	//出现00,30,40…导致无解
				return 0;
			if(s[i]=='0'&&s[i-1]<='2')	//是10,20
				num[2]=num[0];
			else if(s[i-1]=='0'||(s[i-1]-'0')*10+s[i-0]-'0'>26)	//出现大于26
				num[2]=num[1];
			else	//一般情况
				num[2]=num[0]+num[1];
		}
		return num[2];
    }
};


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值