题目:

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和26的限制判断。

Solution 1 ()

class Solution {
public:
int numDecodings(string s) {
if(s.empty() || s.size()> && s.front() == '') return ;
vector<int> dp(s.size()+, );
dp[] = ;
for(int i=; i<dp.size(); i++) {
if(s[i-] == '') dp[i] = ;
else dp[i] = dp[i-];
if(i> && (s[i-] == '' || s[i-] <= '' && s[i-] == ''))
dp[i] += dp[i-];
}
return dp.back();
}
};

Solution 2 ()

class Solution {
public:
int numDecodings(string s) {
if(s.empty() || s.front() == '') return ;
// r2: decode ways of s[i-2] , r1: decode ways of s[i-1]
int r1 = , r2 = ;
for(int i=; i<s.size(); i++) {
// zero voids ways of the last because zero cannot be used separately
if(s[i] == '') r1 = ;
// possible two-digit letter, so new r1 is sum of both while new r2 is the old r1
if(s[i-] == '' || s[i-] == '' && s[i] <= '') {
r1 = r2 + r1;
r2 = r1 - r2;
}
// one-digit letter, no new way added
else r2 = r1;
}
return r1;
}
};
04-15 17:08