摘要:用將子字符串轉化為,參見和的區別然后用動規方法表示字符串的前位到包含方法的個數。最后返回對應字符串末位的動規結果。
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.
ExampleGiven encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.
用parseInt將子字符串轉化為int,參見parseInt和valueOf的區別;
然后用動規方法:
dp[i]表示字符串s的前i位(0到i-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]。
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
摘要:建立動規數組,表示從起點處到達該點的可能性。循環結束后,數組對所有點作為終點的可能性都進行了賦值。和的不同在于找到最少的步數。此時的一定是滿足條件的最小的,所以一定是最優解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...
摘要:這里要注意的是的用法。所以記住,用可以從自動分離出數組。跳過第一個元素并放入數組最快捷語句建立的用意記錄處理過的結點并按處理所有結點和自己的連接下面先通過判斷,再修改的符號的順序,十分巧妙更輕便的解法 Problem Design an algorithm and write code to serialize and deserialize a binary tree. Writin...
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...
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...
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...
閱讀 1202·2021-11-23 09:51
閱讀 1980·2021-10-08 10:05
閱讀 2339·2019-08-30 15:56
閱讀 1900·2019-08-30 15:55
閱讀 2640·2019-08-30 15:55
閱讀 2487·2019-08-30 13:53
閱讀 3498·2019-08-30 12:52
閱讀 1250·2019-08-29 10:57