LeetCode —— Decode Ways
来源:互联网 发布:mac office 2016 破解 编辑:程序博客网 时间:2024/06/01 08:45
链接:http://leetcode.com/onlinejudge#question_91
原题:
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的思想,要小心不合法字符串到出现,我第一次就WA了。
考虑元素s[i],只有两种可能:
1)单独解码,当然s[i] != '0'
2) 和s[i-1]结合了解码,要求 s[i-1]s[i]的值在10~26之间,不然不行。
PS:小心0,00的不合法字符串。
代码:
class Solution {public: int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.size() == 0) return 0; if (s[0] == '0') return 0; vector<int> dp(s.size()+1, 0); dp[0] = dp[1] = 1; for (int n=2; n<=s.size(); n++) { int i = n - 1; if (s[i] != '0') dp[n] = dp[n-1]; int code = (s[i-1]-'0')*10 + (s[i]-'0'); if (code == 0) return 0; else if (code>9 && code<27) dp[n] += dp[n-2]; } return dp[s.size()]; }};
- LeetCode —— Decode Ways
- LeetCode——Decode Ways
- leetcode——Decode Ways
- leetcode笔记—Decode Ways
- leetcode 091 —— Decode Ways
- Leetcode——91. Decode Ways
- Leetcode——639.Decode Ways II
- 动态规划——Decode Ways[LeetCode]
- leetcode由易入难——【4】Decode Ways
- 【leetcode】String——Decode Ways(91)
- leetcode刷题之旅——91. Decode Ways
- Leetcode 91. Decode Ways&&639.Decode ways
- LeetCode: Decode Ways
- [LeetCode]Decode Ways
- LeetCode Decode Ways
- LeetCode : Decode Ways
- [Leetcode] Decode Ways *
- [leetcode] Decode Ways (!!)
- this
- 输出转换
- 杭电2013
- 关于AL32UTF8 导入 AL16UTF16 遇到的问题
- C语言线性非循环单链表
- LeetCode —— Decode Ways
- Windows7中IIS简单安装与配置(详细图解)
- 经常用到的sql
- hdu 3695 AC自动机模板题
- USACO:Score Inflation
- selenium2.0数据驱动测试的应用
- The silver search(ag)比ack-grep还快
- sharePoint 发生意外错误.显示错误详细信息
- 杭电2014