码迷,mamicode.com
首页 > 其他好文 > 详细

639. Decode Ways II

时间:2017-12-16 17:13:05      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:following   ==   encode   its   turn   one   character   mod   ppi   

A message containing letters from A-Z is being encoded to numbers using the following mapping way:

‘A‘ -> 1
‘B‘ -> 2
...
‘Z‘ -> 26

Beyond that, now the encoded string can also contain the character ‘*‘, which can be treated as one of the numbers from 1 to 9.

Given the encoded message containing digits and the character ‘*‘, return the total number of ways to decode it.

Also, since the answer may be very large, you should return the output mod 109 + 7.

Example 1:

Input: "*"
Output: 9
Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".

 

Example 2:

Input: "1*"
Output: 9 + 9 = 18
class Solution {
public:
    int numDecodings(string s) {
        int n = s.size();
        int L = pow(10,9)+7;
        if(n==0) return 0;
        long f1 = 1;
        long f2 = helper(s.substr(0,1));
        for(int i = 1;i<n;i++)
        {
          long f3 = f1*helper(s.substr(i-1,2))+f2*helper(s.substr(i,1));
          f1 = f2;
          f2 = f3%L;
        }
        return f2;
    }
private:
    int helper(string s)
    {
        if(s.size()==1)
        {
            if(s[0]==*) return 9;
            else 
                return s[0]==0?0:1;
        }
    
       if (s == "**")    
            return 15;  
        else if (s[1] ==*) {  
            if (s[0] ==1) return 9;  
            return s[0] == 2? 6:0;  
        }  
        else if (s[0] == *)   
            return s[1] <= 6? 2:1;  
        else   
            return stoi(s) >= 10 && stoi(s) <= 26? 1:0;   
    }
};

 

639. Decode Ways II

标签:following   ==   encode   its   turn   one   character   mod   ppi   

原文地址:http://www.cnblogs.com/jxr041100/p/8046717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!