Decode Ways
2016-06-27 16:24
218 查看
题目描述:
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.
这个题用动态规划的方法做。
cur记录目标数字,pre记录目标前一个数字。然后分类讨论,注意细节就行了。
代码如下:
public class Solution {
public int numDecodings(String s) {
int n=s.length();
if(n==0||s.charAt(0)=='0')
return 0;
int[] nums=new int
;
nums[0]=1;
for(int i=1;i<n;i++){
int cur=s.charAt(i)-'0';
int pre=s.charAt(i-1)-'0';
if(cur==0){
if(pre==1||pre==2){
nums[i]=i==1?1:nums[i-2];
}else{
nums[i]=0;
}
}else if(cur<=6&&cur>=1){
if(pre==2||pre==1){
nums[i]=i==1?2:nums[i-1]+nums[i-2];
}else{
nums[i]=nums[i-1];
}
}else{
if(pre==1){
nums[i]=i==1?2:nums[i-1]+nums[i-2];
}else{
nums[i]=nums[i-1];
}
}
}
return nums[n-1];
}
}
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.
这个题用动态规划的方法做。
cur记录目标数字,pre记录目标前一个数字。然后分类讨论,注意细节就行了。
代码如下:
public class Solution {
public int numDecodings(String s) {
int n=s.length();
if(n==0||s.charAt(0)=='0')
return 0;
int[] nums=new int
;
nums[0]=1;
for(int i=1;i<n;i++){
int cur=s.charAt(i)-'0';
int pre=s.charAt(i-1)-'0';
if(cur==0){
if(pre==1||pre==2){
nums[i]=i==1?1:nums[i-2];
}else{
nums[i]=0;
}
}else if(cur<=6&&cur>=1){
if(pre==2||pre==1){
nums[i]=i==1?2:nums[i-1]+nums[i-2];
}else{
nums[i]=nums[i-1];
}
}else{
if(pre==1){
nums[i]=i==1?2:nums[i-1]+nums[i-2];
}else{
nums[i]=nums[i-1];
}
}
}
return nums[n-1];
}
}
相关文章推荐
- IE6/IE7的兼容问题
- WIN7系统JavaEE(java)环境配置教程(一)
- hive12启动报错org.apache.thrift.server.TThreadPoolServer.<init>(Lorg/apache/thrift/server/TThreadPoolServer$Args;)
- size_t 数据类型深思
- Two Sum Leetcode Python Java
- web前端开发:Http协议
- 移动端高清、多屏适配方案
- Codeforces Round #359 (Div. 2) D. Kay and Snowflake
- 2096小明A+B
- 存储过程定时任务
- 10年乔布斯对flash的思考迎来了web3.0时代(html5的应用)
- [UWP 开发] 一个简单的Toast实现
- CMake学习笔记(4)——使用外部共享库和头文件
- 274. H-Index
- 安卓线程池ThreadPoolExecutor的常见使用
- 如何提高大型工程的编译速度?
- permission 和 user-permission的区别
- win8系统蓝屏提示DRIVER POWER STATE FAILURE的原因及两种解决方法
- 欢迎使用CSDN-markdown编辑器
- 使用Popen运行程序超时就kill