您的位置:首页 > 其它

[leetcode] 91.Decode Ways

2015-06-25 21:25 141 查看
题目:

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.

题意:

字符A—-Z对应的数字是1-26。给定一个数字字符串,判断一共有哪些字符的组成状况。比如“12“,对应的是“AB“或者“L“。

思路:

题目中可能会遇到一些无可能的数字,比如0,00,000之类的。

参照之前做的青蛙跳台阶的思路(即斐波拉切数列的思路),比如

11293:

初始时能够到达第一个数的可能有一种,即令num1=1。能够到达第二个1的可能性有两种,从第一个1往后一步,或者直接一步走两个1,即“11“。所以到达第二个1的可能有两种。初始化完毕。

从第三个数一直到最后一个数字,第三个数字2,能够从它前面的一个位置往后走一步到达,或者从离它两个位置的地方跳两格到达。但是也不一定能够到达,得看是否满足条件。比如能够从前一个位置一步到达,那么需要当前位置不是0。如果需要从两步远到达,那么需要当前位置的前一个位置与当前位置的这两个字符组合成的字符串在”10”到”26”之间。

以上。

代码如下:

class Solution {
public:
int numDecodings(string s) {
if(s.size() == 0 || s[0] == 0)return 0;
int num1 = 1,num2 = 1;
if(!valid(s[0]))num1 = 0;
if(s.size() == 1){
return num1;
}
if(!valid(s[1]))num1 = 0;
if(!valid(s[0],s[1]))num2 = 0;
if(s.size() == 2)return num1 + num2;
if(valid(s[0]) && valid(s[1]))num2 += num1;

int res = 0;
for(int i = 2; i < s.size(); i++){
res = 0;
if(!valid(s[i]))res = 0;
if(valid(s[i-1],s[i]))res += num1;
if(valid(s[i]))res += num2;

num1 = num2;
num2 = res;
}
return res;
}
bool valid(char a){
return (a >= '1' && a <= '9');
}
bool valid(char a,char b){
return (a == '1' || a == '2' && b <= '6');
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: