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.

 

Analyse: Let dp[i] is the decode ways of s[0...i-1].

  If last two characters XY is smaller than 26, XY could be decoded as X,Y or XY (do not consider 0 at this time). dp[i + 1] = dp[i - 1]  + dp[i], where dp[i - 1] is for X, Y and dp[i] is for XY. 

  If s[i] is '0', since the input is always valid, s[i -1] must be combined with s[i]. dp[i + 1] = dp[i]. Else if s[i] is not '0', dp[i + 1] = dp[i - 1] + dp[i + 1].  

Runtime: 4ms. 

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         if(s.empty() || s[0] < '1' || s[0] > '9') return 0;
 5         
 6         int n = s.size();
 7         vector<int> dp(n + 1, 0);
 8         dp[0] = dp[1] = 1;
 9         
10         for(int i = 1; i < n; i++) {
11             int lastTwo = (s[i - 1] - '0' ) * 10 + (s[i] - '0');
12             if(lastTwo > 9 && lastTwo <= 26) dp[i + 1] += dp[i - 1];
13             if(s[i] != '0') dp[i + 1] += dp[i];
14         }
15         return dp[n];
16     }
17 };

 

posted @ 2016-08-07 01:50  amazingzoe  阅读(142)  评论(0编辑  收藏  举报