标签:
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 check(char one) { int tmp=one-‘0‘; return (tmp>=1&&tmp<=9)?1:0; // return one==‘0‘?0:1; } int check(char one, char two) { int tmp=10*(one-‘0‘)+two-‘0‘; return (tmp>=10&&tmp<=26)?1:0; // return (one==‘1‘||(one==‘2‘&&two<=‘6‘))?1:0; } int numDecodings(string s) { if(s.empty())return 0; int len=s.length(); vector<int> f(len,0); if(len==1) { f[0]=check(s[0]); return f[0]; } f[0]=check(s[0]); f[1]=(check(s[0])&&check(s[1]))+check(s[0],s[1]); for (int i=2;i<len;i++) { if(check(s[i]))f[i]+=f[i-1]; if(check(s[i-1],s[i]))f[i]+=f[i-2]; } return f[len-1]; } };
标签:
原文地址:http://www.cnblogs.com/Vae98Scilence/p/4281391.html