Decode Ways

来源:互联网 发布:暴风影音mac版能在线么 编辑:程序博客网 时间:2024/04/30 04:00

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。

class Solution {public:    int numDecodings(string s) {        int dp[10010];        int n = s.length();        if(n == 0) return 0;        if(s[0] == '0') return 0;        memset(dp, 0, sizeof(dp));        dp[0] = 1;        dp[1] = 1;        for(int i = 2; i <= n; ++i) {            int x = s[i-1]-'0';            int y = (s[i-2]-'0')*10+s[i-1]-'0';            bool ok = false;            if(x >= 1 && x <= 26) {                ok = true;                dp[i] += dp[i-1];            }            // 01, 02, ..., 09 是非法的            if(y >= 10 && y <= 26) {                ok = true;                dp[i] += dp[i-2];            }            if(!ok) return 0;        }        return dp[n];    }};


0 0
原创粉丝点击