美文网首页
91. Decode Ways

91. Decode Ways

作者: becauseyou_90cd | 来源:发表于2018-07-27 11:40 被阅读0次

https://leetcode.com/problems/decode-ways/description/

解题思路:

  1. 用动态规划:状态转移方程为:if(first<=9 && first >=1) dp[i] += dp[i - 1] if(second >= 10 && second <= 26) dp[i] += dp[i-2];

代码:
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;
    dp[1] = s.charAt(0) == '0' ? 0 : 1;
    for(int i = 2; i <= len; i++){
        int first = Integer.valueOf(s.substring(i-1, i));
        int second = Integer.valueOf(s.substring(i-2, i));
        if(first<=9 && first >=1)
            dp[i] += dp[i-1];
        if(second >= 10 && second <= 26)
            dp[i] += dp[i-2];
    }
    return dp[len];
}

}

相关文章

  • 91. Decode Ways

    91. Decode Ways 题目:https://leetcode.com/problems/decode-w...

  • LeetCode 91-95

    91. Decode Ways[https://leetcode-cn.com/problems/decode-w...

  • 91. Decode Ways -Python-Leetcode

    91. Decode Ways A message containing letters from A-Z is ...

  • 91. Decode Ways

    https://leetcode.com/problems/decode-ways/description/ 解题...

  • 91. Decode Ways

    题目: A message containing letters from A-Z is being encode...

  • 91. Decode Ways

  • 91. Decode Ways

    这道题和普通的DP题不太一样,用的是top-down的方法。也就是从n开始,而不是从0开始建表。注意dp[ ]的s...

  • 91. Decode Ways

    动态规划问题创建一个长度为n+1的数组来储存子问题的结果.状态转移方程:dp[i] =dp[i-1]当s[i] !...

  • 91. Decode Ways

    A message containing letters from A-Z is being encoded to...

  • 91. Decode Ways

    为什么我常常对做题产生恐惧,因为可能为了一个不算难的问题不知不觉绕进去2个小时,这显然是不值得的。这题就是如此。 ...

网友评论

      本文标题:91. Decode Ways

      本文链接:https://www.haomeiwen.com/subject/dxjwmftx.html