码迷,mamicode.com
首页 > 其他好文 > 详细

Decode Ways

时间:2016-08-07 06:13:19      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Decode Ways

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5745308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!