[leetcode] Decode Ways

来源:互联网 发布:测试长相的软件 编辑:程序博客网 时间:2024/06/07 13:53

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.

参考链接:http://blog.csdn.net/pickless/article/details/11586039

思路:

定义F[i]表示S的子串S[0..i]的decode ways。

假设我们已经知道了F[0]~F[i],现在需要求解F[i+1]。

先不考虑边界,就考虑一般情况:

1.S[i+1] == '0',如果S[i]为'1'或者'2',F[i+1] = F[i],否则无解;

2.如果S[i]为'1',F[i+1] = F[i] + F[i-1](例如"xxxxxx118",可以是"xxxxxx11" + "8",也可以是"xxxxxx1" + "18");

3.如果S[i]为'2',当S[i+1] <= '6'时,F[i+1] = F[i] + F[i-1] (最大的Z为"26","27""28""29"不存在),当S[i+1] > '6'时,F[i+1] = F[i] (例如"xxxxxx28",只能是"xxxxxx2" + "8")。

代码:

class Solution {public:    int numDecodings(string s) {        if(s.size()==0) return 0;        int len=s.size();        int dp[len];        memset(dp,0,sizeof(len));        for(int i=0;i<len;i++){            if(s[i]<'0' || s[i]>'9') return 0;            else if(s[i]=='0'){                if(i==0 || s[i-1]=='0' || s[i-1]>'2') return 0;                else{                    dp[i]=i>1?dp[i-2]:1;                }            }            else{                if(i>0 && (s[i-1]=='1' || s[i-1]=='2' && s[i]<='6')){                    dp[i]=(i>0?dp[i-1]:1)+(i>1?dp[i-2]:1);                }                else{                    dp[i]=i>0?dp[i-1]:1;                }            }        }        return dp[len-1];    }};


0 0
原创粉丝点击