首页 > 学院 > 开发设计 > 正文

91. Decode Ways

2019-11-06 09:28:12
字体:
来源:转载
供稿:网友

问题描述 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.

解决思路 很简单的动态规划的解法,但是需要注意’0’的情况,不同情况状态转移函数不同。

代码

class Solution {public: int numDecodings(string s) { if (s.length() == 0) return 0; if (s.length() == 1 && s[0] >'0' && s[0] <= '9') return 1; else if(s.length() == 1) return 0; if (s[0] == '0') return 0; int len = s.length(); vector<int> dp(len,0); if (dp[0] == '0') dp[0] = 0; else dp[0] = 1; int num = (s[0]-'0') * 10 + (s[1]-'0'); if (num <= 26 && num % 10 != 0 && num > 9) dp[1] = 2; else if ((num > 26 && num%10 != 0) || num == 10 || num == 20) dp[1] = 1; else if (num > 0) return 0; for (int i = 2; i < len; ++i) { if (s[i] == '0' && s[i-1] < '3' && s[i-1] > '0') { dp[i] = dp[i-1] = dp[i-2]; } else if (s[i] == '0') return 0; else { num = (s[i-1]-'0') * 10 + (s[i]-'0'); if (num > 9 && num <= 26) dp[i] = dp[i-1]+dp[i-2]; else dp[i] = dp[i-1]; } } return dp[len-1]; }};
上一篇:test

下一篇:47:Wildcard Matching

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表