首页 > 代码库 > 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.


解题思路:

    刚看题目的时候以为是搜索,在本子上划了一下,发现是道dp的题目,下面说说dp状态的定义.


dp[i]:表示以字符串s[0]...s[i-1]的编码方式有多少种.


对于一个状态dp[i]可能有两种情况:①s[i]映射为一个独立的字母.②s[i-1]与s[i]两个字符映射成一个


字母.需要注意的是字符‘0‘的情况,还有就是s[i-1]与s[i]组合成的整数大于26,只需要处理下特别情况


就可以了,时间复杂度为O(N).


解题代码(12ms):

class Solution 
{
public:
    int numDecodings(string s) 
    {        
       const int n = s.size();
       int dp[n + 1];
       if (!n || s[0] == '0')
           return 0;
       dp[0] = dp[1] = 1;
       for (int i = 1; i < n; ++i)
       {
           if (s[i] == '0')
           {
               if (s[i - 1] == '1' || s[i - 1] == '2')
                   dp[i + 1] = dp[i - 1];
               else
                   return 0;
               continue;
           }
           int num = (s[i - 1] - '0') * 10 + s[i] - '0';
           dp[i + 1] = dp[i] + (num > 9 && num <= 26 ? dp[i - 1] : 0);
       }
       return dp[n];
    }
};


LeetCode:Decode Ways