LeetCode Decode Ways
来源:互联网 发布:java电信资费系统 编辑:程序博客网 时间:2024/05/22 22:27
原题链接在这里:https://leetcode.com/problems/decode-ways/
DP题,保存的历史信息是到历史点有多少种decode的方法,用长度为len+1的数组保存,更新方式是若当前位i 和前一位 i-1两个组合的数字不合法则decode方法并没有增加,仍是dp[i-1]; 若合法,则应更改为dp[i-2]+dp[i-1]. 跟走楼梯相似。
初始化为了方便把dp[0]设成了1, 因为后面的更新可能用到前面两个数字。
Note: isValid是用来判定 string 代表的数字是否合法,若是string 是"09","10", 对应的数字9, 10都在1到26之间,但“0”根本就不能decode, 所以任何包含 "0"的字符串都是非法的,return false.
AC Java:
public class Solution { public int numDecodings(String s) { if(s == null || s.length() == 0){ return 0; } int len = s.length(); int[] dp = new int[len+1]; dp[0] = 1; if(isValid(s.substring(0,1))){ dp[1] = 1; }else{ dp[1] = 0; } for(int i = 2; i<=len; i++){ if(isValid(s.substring(i-1, i))){ dp[i] = dp[i-1]; } if(isValid(s.substring(i-2, i))){ dp[i] += dp[i-2]; } } return dp[len]; } private boolean isValid(String s){ if(s.charAt(0) == '0') { //error return false; } return Integer.valueOf(s)>=1 && Integer.valueOf(s)<=26; }}
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
- HashMap
- 成为Java GC专家(4)—Apache的MaxClients参数详解及其在Tomcat执行FullGC时的影响
- rlimit 介绍
- python之xpath爬虫
- 观察力
- LeetCode Decode Ways
- Python学习笔记(三)
- bzoj-1112 砖块Klo
- hdoj 1870 愚人节的礼物
- Django初学者(一)
- 表格和列表
- lufylegend学习笔记之三
- 浏览器访问网页的详细内部过程
- 【C++】写时拷贝COW