Decode Ways
A message containing letters from
For example,
Given encoded message
The number of ways decoding
*/A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26Given 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:
bool isValidNumber(char c){
return (!(c < '0' || c >'9'));
}
int numDecode(string s, int pos){
if(pos==0){
return 1;
}
if(pos==1){
if(s[0]>'2' || (s[0]=='2' && s[1]>'6') || s.substr(0, pos+1)=="10") return 1;
else return 2;
}
if(s[pos]=='0') return numDecode(s, pos-2);
int num = numDecode(s, pos-1);
if(s[pos-1]=='0' || s[pos-1]>'2' || (s[pos-1]=='2' && s[pos]>'6')){
return num;
}
num = num + numDecode(s, pos-2);
return num;
}
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//validate the input string
int size = s.length();
if(size==0) return 0;
int i;
//validate the input
for(i=0; i<size; i++){
if(!isValidNumber(s[i])) return 0;
if(s[i]=='0'){
if(!(i>=1 && s[i-1]=='1')) return 0;
}
}
return numDecode(s, size-1);
}
};
No comments:
Post a Comment