91. Decode Ways

来源:互联网 发布:卧龙大数据 上市 编辑:程序博客网 时间:2024/05/22 07:56

题目

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.

题意

用1-26标记A-Z.
给一串非0的数字字符串, 求它有多少种解码为合法字母串的方法.
比如12可以解码为AB,也可以解码为L

代码

class Solution {public:    int numDecodings(string s) {        if (s.size() == 0 || s[0] == '0') return 0;        vector<int> dp(s.size()+2, 0);        dp[1] = dp[2] = 1;        for (int i = 3; i < s.size()+2; i++) {            char dt = s[i-3], dg = s[i-2];            if (dg >= '1'&& dg <= '9')                 dp[i] = dp[i-1];            if (dt == '1' || (dt == '2' && dg <= '6'))                dp[i] += dp[i-2];        }        return dp[s.size()+1];     }};