Leetcode(91) Decode Ways
来源:互联网 发布:vb replace函数用法 编辑:程序博客网 时间:2024/05/17 22:17
题目:
计算有多少种不同的编码方式.
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.
动态规划,用f[i]表示前i个元素编码的方式数。因为最后一个编码可能取最后两个数字,也可能只取最后一个数字,所以f[i]=f[i-1]+f[i-2]。注意要判断能不能只取最后一个数字或者取最后两位数字,能取才加上去。边界条件是f[0]和f[1]。
复杂度:O(n)。
代码:
class Solution {public: int numDecodings(string s) { if(s.length()==0) return 0; vector<int> f(s.length(),0); int temp; if(s[0]>'0') f[0]++; if(s.length()==1) return f[0]; if(s[1]>'0') f[1]=f[0]; temp=(s[0]-'0')*10+(s[1]-'0'); if(temp<=26&&temp>=10) f[1]++; for(int i=2;i<s.length();i++) { if(s[i]>'0') f[i]+=f[i-1]; temp=(s[i]-'0')+(s[i-1]-'0')*10; if(temp>=10&&temp<=26) f[i]+=f[i-2]; } return f[s.length()-1]; }};
0 0
- LeetCode 91: Decode Ways
- [leetcode 91] Decode Ways
- [LeetCode 91]Decode Ways
- leetcode || 91、Decode Ways
- Leetcode 91 Decode Ways
- LeetCode(91) Decode Ways
- leetcode 91:Decode Ways
- Leetcode #91 Decode Ways
- leetcode 91: Decode Ways
- LeetCode 91: Decode Ways
- 【leetcode】【91】Decode Ways
- [LeetCode-91] Decode Ways
- leetcode 91 Decode Ways
- LeetCode 91 Decode Ways
- Leetcode 91 Decode Ways
- Leetcode(91) Decode Ways
- Leetcode Decode Ways 91
- LeetCode 91 Decode Ways
- Speech 框架构建语音转文本应用详解
- Spark Streaming + Kafka整合(Kafka broker版本0.8.2.1+)
- [T][10+]洛谷 P1373 小a和uim之大逃离
- 【JVM】故障处理工具VisualVM
- 洛谷 P1525 [NOIP2010 T3] 关押罪犯
- Leetcode(91) Decode Ways
- 阻焊层和助焊层的区别
- java的Class类
- 【结论】【数学】组合数求法
- 《谷歌和亚马逊如何做产品》读书笔记之五:赢在测试
- jsp+servlet+jdbc实现简单的登陆验证
- shell、javascript、python、tcl 等常用脚本语言
- 读书笔记:C++ primer 5th edition--chapter15.OOP
- LeetCode(70) Climbing Stairs