LeetCode 91 Decode Ways
来源:互联网 发布:战舰世界数据端口 编辑:程序博客网 时间:2024/05/21 14:04
原题:(频率4)
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-Z代表1-26 。举例子来说吧, 123,可能是"ABC" ,"BC" "AB" 就是要求得出有多少种可能性
代码和思路:
主要需要了解两个点,如果有个数是0,那么是不对应任何字母的。或者两个数字不在1-26之间,27,也无法对应任何字母。
class Solution { public int numDecodings(String s) { if(s.length() == 0 || s==null){ return 0; } int n = s.length(); //用数组记录到第几个字母所对应有多少种way int [] dp = new int [n+1]; dp[0] = 1; //一个字母的时候,如果不为0,那么有1种way dp[1] = s.charAt(0) != '0'? 1 : 0; //从第二个字母开始遍历 for(int i = 2; i <= n; i++){ //first 代表后面一个数 12中的2 int first = Integer.valueOf(s.substring(i-1, i)); //second则代表两个数 12 int second = Integer.valueOf(s.substring(i-2,i)); //单个数字first不为0,就不会出现断层,前面的 ways 就可以传递过来 if(first >= 1 && first <= 9){ //用数组记录每一个字母所在位置的ways dp[i] += dp[i-1]; } //两个数字在规定范围内,至少保证s[i]到s[i-2]的内容是可以成为一个way的 if(second >= 10 && second <= 26){ dp[i] += dp[i-2]; } } return dp[n]; }}
阅读全文
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
- 定时器cron表达式
- 台湾大学机器学习基石Lecture12
- 固定
- Node.js 单元测试:我要写测试
- (6)Fragment与Activity通信
- LeetCode 91 Decode Ways
- XZ_iOS之Mac搭建nginx+rtmp服务器
- js深拷贝和浅拷贝
- 合并有序数组
- 汉诺塔问题
- HttpClient Features
- 【Machine Learning in Action】Chap8|Predict numeric values--regression
- mysql导出一张表
- 购物