91. Decode Ways
来源:互联网 发布:梁朝伟演技知乎 编辑:程序博客网 时间:2024/05/17 22:36
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.
组合的问题,问一串数字字符串能解码的结果有多少种。这里A~B表示出1~26,所以要注意0。如果一开始就是0,那肯定是不行的,返回0。用动态规划的方法。dp[n]代表前面n个字符的结果。能映射成一个字母的可能只有2种,就是一个数字(1~9)映成一个字母或者两个数字(01~26)映成一个字母,所以dp[n]=(dp[n-1] or 0)+(dp[n-2] or 0),这里or 0是考虑到数字s[n-1]可能不是1~9和数字s[n-2:n]可能不是01~26,如果两个都不符合说明没有结果,返回0。最后返回dp[s的长度]。
代码:
class Solution {public: int numDecodings(string s) { if(s.empty()) return 0; if(s[0]=='0') return 0; int n=s.size(); vector<int>dp(n+1,0); dp[0]=1;dp[1]=1; for(int i=2;i<=n;i++) { if(s[i-1]!='0') dp[i]=dp[i-1]; if(s[i-2]!='0'&&stoi(s.substr(i-2,2))<=26&&stoi(s.substr(i-2,2))>=1) dp[i]+=dp[i-2]; if(dp[i]==0) return 0;}return dp[n]; } };
0 0
- Leetcode 91. Decode Ways&&639.Decode ways
- [Leetcode] 91. Decode Ways
- LeetCode --- 91. Decode Ways
- [LeetCode]91.Decode Ways
- [leetcode] 91.Decode Ways
- 91. Decode Ways
- Algorithms-91.Decode Ways
- [leetcode] 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- 91. Decode Ways
- leetcode 91. Decode Ways
- 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- LeetCode 91. Decode Ways
- 91. Decode Ways
- 闹铃问题
- 第十五周项目 阅读程序(4)
- Codeforces #107 div 2
- TOMCAT JAVA_HOME or JRE_HOME environment variable is not defined correctly
- 《机器学习(周志华)》P19-习题1.1
- 91. Decode Ways
- Eclipse设置反编译环境
- Web服务器的工作原理
- 利用Docker Registry服务实现多数据中心的部署优化
- oracle数据库关键字与语法-工作笔记(随时更新)
- Linux awk 命令
- Android轻量级数据库的建立个基本的操作
- jquery ajax 不能用于下载文件
- zookeeper使用和原理探究(一)