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.
class Solution {
public:
int numDecodings(string s) {
int *dp = new int[s.size()];
memset(dp,0,sizeof(int)*s.size());
if(s.size() == 0) return 0;
if(s.size() == 1) return s[0] == '0' ? 0 : 1;
if(s.size() == 2) return (s[0] != '0' && s[1] != '0' ? 1 : 0) + (s[0] != '0' && ((s[0] - '0') * 10 + s[1] - '0') <= 26 ? 1 : 0);
dp[0] = s[0] == '0' ? 0 : 1;
dp[1] = (s[0] != '0' && s[1] != '0' ? 1 : 0) + (s[0] != '0' && ((s[0] - '0') * 10 + s[1] - '0') <= 26 ? 1 : 0);
for(int i = 2;i < s.size();i ++){
if(s[i] != '0')
dp[i] += dp[i - 1];
if(s[i - 1] != '0' && ((s[i - 1] - '0') * 10 + s[i] - '0') <= 26)
dp[i] += dp[i - 2];
}
return dp[s.size() - 1];
}
};
本文介绍了一种基于动态规划的消息解码算法,该算法能够计算出给定数字编码字符串的可能字母组合数量。通过递归地考虑单个字符和连续两个字符的情况,可以有效地解决这一问题。
224

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



