题目
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];
}
};
本文介绍了一种解码计数算法,该算法用于确定给定编码消息中可能的解码方式的数量。通过分析不同字符组合的可能性,算法可以高效地解决这一问题。特别关注了特殊情况的处理,例如出现特定字符序列时的解码规则。
222

被折叠的 条评论
为什么被折叠?



