国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Decode Ways [String to Integer

andong777 / 2376人閱讀

摘要:用將子字符串轉化為,參見和的區別然后用動規方法表示字符串的前位到包含方法的個數。最后返回對應字符串末位的動規結果。

Problem

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.

Example

Given encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.

Note

parseInt將子字符串轉化為int,參見parseIntvalueOf的區別;
然后用動規方法:
dp[i]表示字符串s的前i位(0i-1)包含decode方法的個數。
若前一位i-2到當前位i-1的兩位字符串s.substring(i-2, i)對應的數字lastTwo在10到26之間,則當前位dp[i]要加上這兩位字符之前一個字符對應的可能性:dp[i-2];
若當前位i-1的字符對應1到9之間的數字(不為0),則當前dp[i]要加上前一位也就是第i-2位的可能性:dp[i-1]
最后返回對應字符串s末位的動規結果dp[n]

Solution updated 2018-9
class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0) return 0;
        int n = s.length();
        int[] dp = new int[n+1];
        dp[0] = 1;                                                  //if the first two digits in [10, 26]
        dp[1] = s.charAt(0) == "0" ? 0 : 1;
        for (int i = 2; i <= n; i++) {
            if (s.charAt(i-1) != "0") dp[i] += dp[i-1];             //XXX5X
            int lastTwo = Integer.parseInt(s.substring(i-2, i));
            if (lastTwo >= 10 && lastTwo <= 26) dp[i] += dp[i-2];   //XXX10X
        }
        return dp[n];
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65974.html

相關文章

  • [LintCode/LeetCode] Jump Game I & II

    摘要:建立動規數組,表示從起點處到達該點的可能性。循環結束后,數組對所有點作為終點的可能性都進行了賦值。和的不同在于找到最少的步數。此時的一定是滿足條件的最小的,所以一定是最優解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...

    rose 評論0 收藏0
  • [LintCode/LeetCode] Binary Tree Serialization

    摘要:這里要注意的是的用法。所以記住,用可以從自動分離出數組。跳過第一個元素并放入數組最快捷語句建立的用意記錄處理過的結點并按處理所有結點和自己的連接下面先通過判斷,再修改的符號的順序,十分巧妙更輕便的解法 Problem Design an algorithm and write code to serialize and deserialize a binary tree. Writin...

    keithyau 評論0 收藏0
  • 91. Decode Ways

    A message containing letters from A-Z is being encoded to numbers using the following A -> 1 B -> 2 ... Z -> 26 For example, Given encoded message 12, it could be decoded as AB (1 2) or L (12). The n...

    macg0406 評論0 收藏0
  • [LintCode/LeetCode] Integer Replacement

    Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...

    fyber 評論0 收藏0
  • [LintCode/LeetCode] Min Stack/Max Stack

    Problem Implement a stack with min() function, which will return the smallest number in the stack. It should support push, pop and min operation all in O(1) cost. Example push(1)pop() // return 1pus...

    GHOST_349178 評論0 收藏0

發表評論

0條評論

andong777

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<