Decode Ways

来源:互联网 发布:网络发射器和接收器 编辑:程序博客网 时间:2024/05/17 07:24

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) {        int len = s.length();        if(len <= 0)        {        return 0;        }        int *dp = new int[len + 1];//多一个空间方便处理        dp[len] = 1;//如果倒数第二个可以和倒数第一个形成两位码,要用到它        dp[len - 1] = s[len - 1] == '0' ? 0 : 1;//当倒数第一个为‘0’时,不计数        for(int i = len - 2; i >= 0; i--)        {        dp[i] = 0;        if((s[i] == '1' && s[i + 1] <= '9') || (s[i] == '2' && s[i + 1] < '7'))//当时没搞清s[i]和s[i+1]的关系,在这里坑了几次        {        dp[i] += dp[i + 2];        }        if(s[i] != '0' && s[i + 1] != '0')        {        dp[i] += dp[i + 1];        }        }        int res = dp[0];        delete dp;        return res;    }};



0 0
原创粉丝点击