当前位置:编程学习 > C/C++ >>

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:
 
 
int numDecodings(string s) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        int length = s.size();  
        if(length<1)return 0;  
        int* dp = new int[length+1];  
        memset(dp, 0, sizeof(int)*(length+1));  
        dp[0] = 1;  
        if(s[0] == '0')dp[1] = 0;  
        else dp[1] = 1;  
        for(int i = 2; i <= length; ++i)  
        {  
            int num = stoi(s.substr(i-1,1));  
            if(num > 0)  
                dp[i] = dp[i-1];  
            num = stoi(s.substr(i-2,2));  
            if(num > 9 && num < 27)  
                dp[i] += dp[i-2];  
        }  
        int res = dp[length];  
        delete[] dp;  
        return res;  
    }  

 

 
 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,