首页 > 其他 > 详细

【65】91. Decode Ways

时间:2017-02-12 19:02:52      阅读:184      评论:0      收藏:0      [点我收藏+]

91. Decode Ways

Description Submission Solutions Add to List

  • Total Accepted: 104110
  • Total Submissions: 548557
  • Difficulty: Medium
  • Contributors: Admin

 

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.

class Solution {
public:
    int numDecodings(string s) {
        if(s.empty()) return 0;
        int n = s.size();
        vector<int> dp(n + 1, 0);
        dp[0] = 1;
        for(int i = 1; i <= n; i++){
            dp[i] += s[i - 1] == 0 ? 0 : dp[i - 1];
            if(i >= 2 && s.substr(i - 2, 2) >= "10" && s.substr(i - 2, 2) <= "26"){
                dp[i] += dp[i - 2];//其实就是dp[i] = dp[i - 1] + dp[i - 2] 因为当是两位数时,有两种decode的方法
            }
        }
        return dp[n];
    }
};

 

 
 
 
 

【65】91. Decode Ways

原文:http://www.cnblogs.com/93scarlett/p/6391455.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!