[LeetCode] 026: Decode Ways

[Problem]

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.

[Analysis]
S[i:n] = S[i+1:n] + S[i+2:n],即,i~n的字符串可以将i单独解码,也可以将i和i+1联合解码,S[i:n]表示字符串i~n的解码种数。
注意:单独解码时,0是不能被解码的。

[Solution]
class Solution {
public:
// if the string could be decoded as a character
bool canBeDecoded(string s){
// invalid string
if(s.size() <= 0 || s.size() > 2)return false;

// 1 ~ 9
if(s.size() == 1 && s[0] >= '1' && s[0] <= '9')return true;

// two digits
if(s.size() == 2){
// 10 ~ 19
if(s[0] == '1' && s[1] >= '0' && s[1] <= '9')return true;

// 20 ~ 26
if(s[0] == '2' && s[1] >= '0' && s[1] <= '6')return true;
}
return false;
}

// get the number of decoding ways of the string
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// empty string
if(s.size() == 0)return 0;

// if the s is valid: all characters are digit
for(int i = 0; i < s.size(); ++i){
if(!(s[i] >= '0' && s[i] <= '9'))return 0;
}

// decode
int count[s.size()];
memset(count, 0, sizeof(count));
for(int i = s.size()-1; i >= 0; --i){
// decoded as itself
if(s[i] > '0'){
if(i+1 >= s.size()){
count[i] += 1;
}
else if(count[i+1] > 0){
count[i] += count[i+1];
}
}

// decoded with the next character
if(i+1 < s.size() && canBeDecoded(s.substr(i, 2))){
if(i+2 >= s.size()){
count[i] += 1;
}
else if(count[i+2] > 0){
count[i] += count[i+2];
}
}
}

return count[0];
}
};
说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值