题目:

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.

链接: http://leetcode.com/problems/decode-ways/

题解:

一看到这题就想到了爬楼梯climb stairs,典型的一维DP。下面就用一维DP来做。先建立数组dp = new int[s.length() + 1], 初始化一个数字的情况dp[0] = 1, 两个数字组成一个两位数字的情况dp[1] = 1。接下来写出循环体,先算一个数字的情况,当s.charAt(i - 1)不为0的时候,dp[i] = dp[i - 1], 否则dp[i] = 0。 接下来考虑两位数字,当由i-2和i-1这两位组成的数字大于等于10,小于等于26时,dp[i] += dp[i - 2], 否则忽略此种情况。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
public int numDecodings(String s) {
if(s == null || s.length() == 0 || s.charAt(0) == '0')
return 0;
int[] dp = new int[s.length() + 1];
dp[0] = 1;
dp[1] = 1; for(int i = 2; i < dp.length; i++) {
int num = Integer.parseInt(s.substring(i - 2, i));
int twoStepsBehind = (num <= 26 && num >= 10) ? dp[i - 2] : 0;
int oneStepBehind = s.charAt(i - 1) != '0' ? dp[i - 1] : 0;
dp[i] = twoStepsBehind + oneStepBehind;
} return dp[s.length()];
}
}

可以继续优化Space Complexity至O(1).

public class Solution {
public int numDecodings(String s) {
if(s == null || s.length() == 0 || s.charAt(0) == '0')
return 0; int first = 1;
int second = 1; for(int i = 2; i < s.length() + 1; i++) {
int num = Integer.parseInt(s.substring(i - 2, i));
int twoStepsBehind = (num >= 10 && num <= 26) ? first : 0;
int oneStepBehind = s.charAt(i - 1) != '0' ? second : 0;
first = second;
second = twoStepsBehind + oneStepBehind;
} return second;
}
}

题外话: 使用DP思想的一些题目 - decode ways, climb stairs, find LCS(longest common subsequence), find longest ascending subsequence, fine longest descending subsequens, 背包问题,poj滑雪,等等。DP这种重要的编程思想要好好学习领会。

二刷:

还是使用dp,新建一个dp数组比较好理解,但空间的优化却不是很熟练。对于dp,还是需要加强狠练。如何才能写出优雅而且精炼的代码是个问题。 Elegant and concise

Java:

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
public int numDecodings(String s) {
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int len = s.length();
int[] numWays = new int[len + 1];
numWays[0] = 1; // empty string
numWays[1] = 1; // one char
for (int i = 2; i <= len; i++) {
int num = Integer.parseInt(s.substring(i - 2, i));
numWays[i] = (num <= 26 && num >= 10) ? numWays[i - 2] : 0;
numWays[i] += (s.charAt(i - 1) != '0') ? numWays[i - 1] : 0;
}
return numWays[len];
}
}

因为do[i] 只和dp[i - 1]以及dp[i - 2]有关,我们可以优化空间到O(1)。就是使用两个变量来代表numWays[i - 1]和numWays[i - 2], 以及一个变量res来代表它们的和,接下来三个一起倒腾倒腾就好了

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
public int numDecodings(String s) {
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int len = s.length();
int lastTwoSteps = 1; // empty string
int lastOneStep = 1; // one char
int res = 0;
for (int i = 2; i <= len; i++) {
int num = Integer.parseInt(s.substring(i - 2, i));
res += (num <= 26 && num >= 10) ? lastTwoSteps : 0;
res += (s.charAt(i - 1) != '0') ? lastOneStep : 0;
lastTwoSteps = lastOneStep;
lastOneStep = res;
res = 0;
}
return lastOneStep;
}
}

题外话:

2/11/2016:

时间相当紧张,要复习LC,刷面经,多线程,设计模式,系统设计。自己提速却不是很成功,转进努力吧。要深入思考。

自己与去年9月开始刷题以来,有什么改变和进步呢??? 好像并没有实质性的突破....要说进步的地方,可能就是养成了学习的习惯吧

Reference:

https://leetcode.com/discuss/49719/dp-with-easy-understand-java-solution

https://leetcode.com/discuss/8527/dp-solution-java-for-reference

91. Decode Ways的更多相关文章

  1. leetcode@ [91] Decode Ways (Dynamic Programming)

    https://leetcode.com/problems/decode-ways/ A message containing letters from A-Z is being encoded to ...

  2. Leetcode 91. Decode Ways 解码方法(动态规划,字符串处理)

    Leetcode 91. Decode Ways 解码方法(动态规划,字符串处理) 题目描述 一条报文包含字母A-Z,使用下面的字母-数字映射进行解码 'A' -> 1 'B' -> 2 ...

  3. 【LeetCode】91. Decode Ways 解题报告(Python)

    [LeetCode]91. Decode Ways 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fux ...

  4. [LeetCode] 91. Decode Ways 解码方法

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

  5. leetcode 91 Decode Ways I

    令dp[i]为从0到i的总方法数,那么很容易得出dp[i]=dp[i-1]+dp[i-2], 即当我们以i为结尾的时候,可以将i单独作为一个字母decode (dp[i-1]),同时也可以将i和i-1 ...

  6. 91. Decode Ways反编译字符串

    [抄题]: A message containing letters from A-Z is being encoded to numbers using the following mapping: ...

  7. leetcode 91 Decode Ways ----- java

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

  8. 【LeetCode】91. Decode Ways

    题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: ' ...

  9. 【一天一道LeetCode】#91. Decode Ways

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 A messa ...

随机推荐

  1. mysql主从集群定时备份脚本

    #!/bin/bash   dpath="/mysql_backup" mydays="7" username="root" mysql_p ...

  2. (转载)Cocos2dx-OpenGL ES2.0教程:你的第一个立方体(5)

    在上篇文章中,我们介绍了VBO索引的使用,使用VBO索引可以有效地减少顶点个数,优化内存,提高程序效率. 本教程将带领大家一起走进3D–绘制一个立方体.其实画立方体本质上和画三角形没什么区别,所有的模 ...

  3. mysql-community-server 5.7.16 设置密码

    那是由于mysql-community-server 5.7的密码是一个默认的随机密码,这个初始密码,mysql又不告诉你,我们需要重设这个密码. service mysqld stop mysqld ...

  4. (转)Linux 文件系统:procfs, sysfs, debugfs 用法简介

    网址:http://www.tinylab.org/show-the-usage-of-procfs-sysfs-debugfs/ 1 前言 内核中有三个常用的伪文件系统:procfs,debugfs ...

  5. java第五课:方法

    方法交换位置的三个步骤:1.把第一个盒子里的东西拿出来,放到一边2.把第二个盒子里的东西放到第一个盒子里3.捡起刚刚放到一边的东西,放到第二个盒子里 值传递:实际参数将内部保存的值,复制给方法的参数. ...

  6. ionicPopup确认对话框

    $ionicPopup.confirm({ title: $rootScope.app_name, template: 'Do you want to add this to database?', ...

  7. 读书笔记 (一) ———Fundamentals of Multiagent Systems with NetLogo Examples by Prof. Jose M Vidal

    在网上发现Prof. Jose M Vidal用NetLogo仿真Multi-agent system的视频,随后下载他的著作Fundamentals of Multiagent Systems wi ...

  8. C#中结构体与字节流互相转换

    1.定义与C++对应的C#结构体 在c#中的结构体不能定义指针,不能定义字符数组,只能在里面定义字符数组的引用. C++的消息结构体如下: //消息格式 4+16+4+4= 28个字节 struct ...

  9. MySQL 主主同步配置和主从配置步骤

    ★预备知识 : 1.双机热备 对于双机热备这一概念,我搜索了很多资料,最后,还是按照大多数资料所讲分成广义与狭义两种意义来说. 从广义上讲,就是对于重要的服务,使用两台服务器,互相备份,共同执行同一服 ...

  10. 【高斯消元】BZOJ 1013: [JSOI2008]球形空间产生器sphere

    Description 有一个球形空间产生器能够在n维空间中产生一个坚硬的球体.现在,你被困在了这个n维球体中,你只知道球面上n+1个点的坐标,你需要以最快的速度确定这个n维球体的球心坐标,以便于摧毁 ...