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.
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution {//只考虑需要提取的情况,不要混乱 2 public: 3 int numDecodings(string s) { 4 int ans=0; 5 int len=s.length(); 6 if(!len||s[0]=='0') 7 return 0; 8 vector<int> j(len,0); 9 j[0]=1; 10 for(int i=1;i<len;i++) 11 { 12 if(s[i]>='1'&&s[i]<='9')//单独解码的情况 13 j[i]+=j[i-1]; 14 if(s[i]==0&&(s[i-1]==0||s[i-1]>='3'&&s[i-1]<='9')) 15 return 0; 16 int t=(s[i-1]-'0')*10+s[i]-'0'; 17 if(t>=10&&t<=26) //合并解码的情况 18 { 19 if(i==1) 20 j[i]++; 21 else 22 j[i]+=j[i-2]; 23 } 24 25 } 26 return j[len-1]; 27 } 28 };