【DP】Decode Ways
来源:互联网 发布:php safe mode 开关 编辑:程序博客网 时间:2024/04/30 05:16
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.
public class Solution { private int count = 0; public boolean isDigit(String s){ if(s==null) return false; int len = s.length(); if(len==0 || len>2) return false; int sum = 0; for(int i=0; i<len; i++){ sum = sum * 10 + s.charAt(i) - '0'; } if(sum >26 || sum ==0) return false; return true; } public void dfs(String s, int pos){ if(pos == s.length()){ count++; return; } for(int i=1; i<3 && pos+i<s.length(); i++){ String str = s.substring(pos, pos+i); if(isDigit(str)){ dfs(s, pos+i); } } } public int numDecodings(String s) { dfs(s, 0); return count; }}
解法二:DP
public class Solution { public boolean isValid(String s){ if(s.charAt(0) == '0') return false; int sum = 0; for(int i=0; i<s.length(); i++){ sum = sum * 10 + s.charAt(i) - '0'; } if(sum <= 26) return true; return false; } public int numDecodings(String s) { if(s == null ) return 0; int count = 0; int len = s.length(); if(len == 0) return 0; int d[] = new int[len+1]; d[0] = 1; if(isValid(s.substring(0, 1))) d[1] = 1; else d[1] = 0; for(int i=2; i<=len; i++){ if(isValid(s.substring(i-1, i))) d[i] += d[i-1]; if(isValid(s.substring(i-2, i))){ d[i] += d[i-2]; } } return d[len]; }}
0 0
- 【DP】Decode Ways
- Decode Ways [leetcode] DP
- 【Leetcode】Decode Ways (DP)
- DP Decode Ways
- [LeetCode] Decode Ways(!!!DP)
- DP-----91. Decode Ways
- leetcode---decode-ways--dp
- 91:Decode Ways【DP】【字符串】
- leetcode -- Decode Ways -- dp题目
- 91. Decode Ways (dp)
- LeetCode-91-Decode Ways DP
- Leetcode 91 - Decode Ways(dp)
- 【DP】递推【91. Decode Ways】
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- HCE技术实战分析
- 《编程之美》中黑球,白球各100,问最后剩下一个是黑球的概率
- Libgd实现透明度动作,即实现Actions.alpha方式
- Linux内核链表的浅析和模拟
- Shiro 注解的使用
- 【DP】Decode Ways
- IOS 创建计算器
- ArcGlobe三维开发之四——设置globe图层的缓存属性)
- 上拉下拉刷新终结版---你需要替换的地方
- JS面向对象编程基础部分(2) 3.31
- 一些运维问题
- 用tcpdump在android上抓包
- CSDN 2014 开源技术大会实录
- 23种设计模式之python实现--Bridge模式