(Version 0.0)
Decode ways This problem is theoretically a relatively simple one-dimensional DP topic, with a one-dimensional array of elements dp[i] (I >= 1) to record the starting from the beginning of the length of I substring how many kinds of Decode ways.
However, the actual operation of the first write or in the input as "0" when the error, and the first time when writing did not realize when it can constitute "10" and "20" when the dp[i] to be equal to dp[i-2], but not to take dp[i-1] + dp[i-2], another easy point is for dp[0] The initialization should be 1 instead of 0. The overall feeling of the problem as long as there is DP thinking is not difficult, but to consider the choice of various circumstances and corner case. The code is as follows:
1 Public classSolution {2 Public intnumdecodings (String s) {3 if(S.length () < 2) {4 returnS.equals ("0")? 0:s.length ();//don ' t forget to check if S is "0"5 }6 int[] DP =New int[S.length () + 1];7Dp[0] = 1;//Is careful with this initialization8DP[1] = S.charat (0) = = ' 0 '? 0:1;9 for(inti = 2; i < dp.length; i++) {Ten intval = integer.valueof (s.substring (i-2, i)); One if(val = = 0) { A return0; -}Else if(Val <= 9) { -Dp[i] = dp[i-1]; the}Else if(Val < 27) { - if(val% 10 = = 0) { -Dp[i] = dp[i-2]; -}Else { +Dp[i] = dp[i-1] + dp[i-2]; - } +}Else { A if(val% 10 = = 0) { at return0; -}Else { -Dp[i] = dp[i-1]; - } - } - } in returnDp[dp.length-1]; - } to}
The idea in the loop is roughly, if the current char cannot form a valid number with the previous char, dp[i] = dp[i-1]; If the current char is 0 and the previous one is 0 or the previous char is greater than 2, then this decoding invalid, can return 0 directly If the current char can be a valid number with the previous char, you need to add the elements from the first two DP as the values of the current element, because adding the current char to the previous substring adds two possibilities, that is, to combine with the previous char or not, and, if so, to have a dp[i-2] species, Do not combine the dp[i-1] species, so the total is dp[i-1] + dp[i-2] species.
[Leetcode] Decode Ways