LeetCode#91. Decode Ways
来源:互联网 发布:东坡软件下载 编辑:程序博客网 时间:2024/06/15 08:26
- 题目:大写字母A-Z分别对应1-26,给定一串数字字符串,求这串字符串解码为大写字母有多少种解码结果
- 例子:“12”对应解码有 A 或者 L,所以返回结果是2
- 难度:Medium
思路:一开始我想用递归做,但是没把情况都考虑全。后来看Discuss里的DP方法
自左向右求解,从第1个元素(字符串中下标为0)到第i个元素的解码结果存储在result[i]里
第i个元素之前(包括第i个元素)的所有解码结果:如果这个元素不等于0则它可以自己对应A-Z的某一个元素 所以result[i] 等于 result[i-1]
如果这个元素和前一个元素组成的两个字符是在“10”和“26”之间,result[i]的结果就在result[i]的基础上加上result[i-2]
- 代码:
public class Solution { public int numDecodings(String s) { int len = s.length(); if(s == null || len == 0){ return 0; } int[] result = new int[len+1]; result[0] = 1; result[1] = s.charAt(0) == '0' ? 0:1; for(int i = 2; i <= len; i++){ if(s.charAt(i-1) != '0') result[i] += result[i-1]; int val = Integer.parseInt(s.substring(i-2,i)); if(val >= 10 && val <= 26){ result[i] += result[i-2]; } } return result[len]; }}
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
- [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
- java Stringbuffer的使用
- 100003. Tree
- CodeForces
- C#中DllImport用法汇总
- hdu2852 KiKi's K-Number 线段树
- LeetCode#91. Decode Ways
- Week Training: 452 Minimum Number of Arrows to Burst Balloons
- 螺旋矩阵 II
- 客户端显示2008连接上却实2005数据库
- prophet:时间序列预测模型原理
- Shell 编程入门
- simple_factory
- Leetcode: Set Matrix Zeroes
- 支付宝安卓端调用说明