您的位置:首页 > 其它

91. Decode Ways

2017-02-26 23:03 113 查看
问题描述

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.

解决思路

很简单的动态规划的解法,但是需要注意’0’的情况,不同情况状态转移函数不同。

代码

class Solution {
public:
int numDecodings(string s) {
if (s.length() == 0)
return 0;
if (s.length() == 1 && s[0] >'0' && s[0] <= '9')
return 1;
else if(s.length() == 1)
return 0;
if (s[0] == '0')
return 0;
int len = s.length();
vector<int> dp(len,0);
if (dp[0] == '0')
dp[0] = 0;
else
dp[0] = 1;
int num = (s[0]-'0') * 10 + (s[1]-'0');
if (num <= 26 && num % 10 != 0 && num > 9)
dp[1] = 2;
else if ((num > 26 && num%10 != 0) || num == 10  || num == 20)
dp[1] = 1;
else if (num > 0)
return 0;
for (int i = 2; i < len; ++i) {
if (s[i] == '0' && s[i-1] < '3' && s[i-1] > '0') {
dp[i] = dp[i-1] = dp[i-2];
} else if (s[i] == '0')
return 0;
else {
num = (s[i-1]-'0') * 10 + (s[i]-'0');
if (num > 9 && num <= 26)
dp[i] = dp[i-1]+dp[i-2];
else
dp[i] = dp[i-1];
}
}
return dp[len-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: