LeetCode:Decode Ways
来源:互联网 发布:seo方案ppt 编辑:程序博客网 时间:2024/06/06 02:26
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的题目,下面说说dp状态的定义.
dp[i]:表示以字符串s[0]...s[i-1]的编码方式有多少种.
对于一个状态dp[i]可能有两种情况:①s[i]映射为一个独立的字母.②s[i-1]与s[i]两个字符映射成一个字母.需要注意的是字符'0'的情况,还有就是s[i-1]与s[i]组合成的整数大于26,只需要处理下特别情况就可以了,时间复杂度为O(N).
解题代码:
class Solution {public: int numDecodings(string s) { const int n = s.size(); int dp[n + 1]; if (!n || s[0] == '0') return 0; dp[0] = dp[1] = 1; for (int i = 1; i < n; ++i) { if (s[i] == '0') { if (s[i - 1] == '1' || s[i - 1] == '2') dp[i + 1] = dp[i - 1]; else return 0; continue; } int num = (s[i - 1] - '0') * 10 + s[i] - '0'; dp[i + 1] = dp[i] + (num > 9 && num <= 26 ? dp[i - 1] : 0); } return dp[n]; }};
0 0
- 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 (!!)
- leetcode 17: Decode Ways
- Leetcode: Decode ways
- LeetCode Decode Ways
- [LeetCode]Decode Ways
- [leetcode] Decode Ways
- Leetcode: Decode Ways
- [LeetCode] Decode Ways
- [leetcode]Decode Ways
- LeetCode-Decode Ways
- [leetcode] Decode Ways
- [LeetCode] Decode Ways
- mac上连接iphone进行真机抓包
- H-index因子
- ASP.NET MVC中实现多个按钮提交的几种方法
- 【金阳光测试】大话Android自动化测试--Android自动化系列(1)--金阳光于2013年4月份
- selenium学习
- LeetCode:Decode Ways
- WPF 自定义窗体
- 学习笔记——深度循环的跳出
- iScroll.js
- Qt窗口的删除、析构
- PDF数据防扩散系统方案
- CSDN博客导出工具 Mac By Swift
- Android 下载APK 安装APK 打开APK
- 笑话