Decode Ways

来源:互联网 发布:北京信索咨询集团知乎 编辑:程序博客网 时间:2024/05/16 14:42

题目:

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.

分析:可以用贪心的思想,而且当前数字只与前面的数字有关。

代码如下:

int numDecodings(string s) {
        int n=s.size();
        if(n==0)return 0;
        int *result=new int[n+1];
        memset(result,0,(n+1)*sizeof(int));
        result[0]=1;
        for(int i=1;i<=n;i++)
        {
            if(s[i-1]!='0')
            {
                result[i]+=result[i-1];
            }
            if(i>=2&&s[i-1]-'0'+10*(s[i-2]-'0')<=26&&s[i-1]-'0'+10*(s[i-2]-'0')>=10)
            {
                result[i]+=result[i-2];
            }
        }
        return result[n];
    }


原创粉丝点击