Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

LeetCode: 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.

地址:https://oj.leetcode.com/problems/decode-ways/

算法:动态规划。用dp[i]表示前面i个数字的总共解码方式,则dp[i+1]按如下方法求,如果S[i]为0,则判断S[i-1]是否为1或2,若是则dp[i+1]=dp[i-1],若不是则返回零(因为此时肯定不存在合理的解码方式);如果S[i]不等零,则dp[i+1]至少等于dp[i],如果此时S[i-1]和S[i]取值合理的话,那么还应该加上dp[i-1]。代码:

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         if(s.empty())   return 0;
 5         if(s[0] == '0') return 0;
 6         int len = s.size();
 7         vector<int> dp(len+1);
 8         dp[0] = 1;
 9         dp[1] = 1;
10         for(int i = 2; i <= len; ++i){
11             if(s[i-1] == '0'){
12                 if(s[i-2] == '1' || s[i-2] == '2'){
13                     dp[i] = dp[i-2];
14                     continue;
15                 }else{
16                     return 0;
17                 }
18             }
19             dp[i] = dp[i-1];
20             if(s[i-2] != '0'){
21                 int val = (s[i-2] - '0') * 10 + s[i-1] - '0';
22                 if(val > 0 && val < 27)
23                     dp[i] += dp[i-2];
24             }
25         }
26         return dp[len];
27     }
28 };

 

posted on 2014-08-31 22:37  Boostable  阅读(250)  评论(0编辑  收藏  举报