leetcode91 Decode Ways

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.

 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 };
View Code

 

posted @ 2016-01-06 16:07  西小贝  阅读(198)  评论(0编辑  收藏  举报