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 decode(const string &s,int begin,int end){
int num=0;
for(int i=begin;i<=end;i++){
num=num*10+s[i]-'0';
}
return num;
}
int numDecodings(string s) {
if(s.empty()||s.size()==0){
return 0;
}
int n=s.size(),index=n-1,temp=0;
vector<int> nums(n+1,0);
nums[n]=1;
while(index>=0){
if(s[index]>='1'&&s[index]<='9'){
nums[index]+=nums[index+1];
}
if(index<n-1&&(s[index]=='1'||s[index]=='2')){
temp=decode(s,index,index+1);
if(temp>=10&&temp<=26){
nums[index]+=nums[index+2];
}
}
index--;
}
return nums[0];
}
};