LeetCode: Decode Ways

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 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/boostable/p/leetcode_decode_ways.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值