【65】91. Decode Ways

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

 

 
 
 
 
posted @ 2017-02-12 18:06  会咬人的兔子  阅读(131)  评论(0编辑  收藏  举报