Decode Ways
来源:互联网 发布:淘宝发布类目受到限制 编辑:程序博客网 时间:2024/06/06 13:20
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.
从头到尾扫这个String,比如我们想知道到,从第一位到dp[i]这一位组成的String,有多少种解码组合,那么有两种情况
第一:如果dp[i]所对应的的单个字符可以解码,那么dp[i]就包括前dp[i-1]位所积累的组合数 dp[i] = dp[i-1]
第二:如果不仅dp[i]所对应的的单个字符可以解码,dp[i-1] - dp[i],两个字符组成的也可以解码,那么不仅包括dp[i-1]积累的组合数,也包括dp[i-2]位积累的组合数 dp[i] = dp[i-1] + dp[i-2]
注意:dp的i跟string的i不一样,string的i还要dp的index-1才是string的index;
public class Solution { public int numDecodings(String s) { if(s == null || s.length() == 0) return 0; int[] dp = new int[s.length()+1]; dp[0] = 1; for(int i=1; i<dp.length; i++){ if(isvalid(s.substring(i-1,i))){ dp[i] = dp[i-1]; } if(i-2>=0 && isvalid(s.substring(i-2,i))){ dp[i] +=dp[i-2]; } } return dp[s.length()]; } public boolean isvalid(String str){ if(str == null || str.length() == 0 || str.charAt(0) == '0') return false; int val = Integer.parseInt(str); return (1<=val && val<=26); }}
0 0
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- 全选和反选
- ajax 与 response 对应的关系 设置
- 定义QlikView中的系统字段
- UIScrollView 实践经验
- Vim的常用命令技巧
- Decode Ways
- 社説 20141219 パキスタン襲撃 テロ封じへ国際協調を強めよ
- cdh5 hadoop redhat 本地仓库配置
- eclipse 打jar包
- Rich feature hierarchies for accurate object detection and semantic segmentation(译)
- 社説 20141219 高浜原発「合格」 再稼働に政府支援が不可欠だ
- SQL Server常用技巧
- Rexsee传感器处理
- 立此存照(20)[C++]C++ Primer(4th)消息处理示例