|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** |
4 |
| - * 91. Decode Ways |
5 |
| - * |
6 |
| - * A message containing letters from A-Z is being encoded to numbers using the following mapping: |
7 |
| -
|
8 |
| - 'A' -> 1 |
9 |
| - 'B' -> 2 |
10 |
| - ... |
11 |
| - 'Z' -> 26 |
12 |
| - Given an encoded message containing digits, determine the total number of ways to decode it. |
13 |
| -
|
14 |
| - For example, |
15 |
| - Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). |
16 |
| -
|
17 |
| - The number of ways decoding "12" is 2. |
18 |
| - */ |
19 | 3 | public class _91 {
|
20 |
| - /**Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation |
| 4 | + /** |
| 5 | + * Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation |
21 | 6 | * I used a dp array of size n + 1 to save subproblem solutions.
|
22 | 7 | * dp[0] means an empty string will have one way to decode,
|
23 | 8 | * dp[1] means the way to decode a string of size 1.
|
24 |
| - * |
25 | 9 | * I then check one digit and two digit combination and save the results along the way.
|
26 |
| - * In the end, dp[n] will be the end result.*/ |
| 10 | + * In the end, dp[n] will be the end result. |
| 11 | + */ |
27 | 12 |
|
28 | 13 | public static class Solution1 {
|
29 |
| - public int numDecodings(String s) { |
30 |
| - if (s == null || s.length() == 0) { |
31 |
| - return 0; |
32 |
| - } |
33 |
| - int[] dp = new int[s.length() + 1]; |
34 |
| - dp[0] = 1; |
35 |
| - dp[1] = (s.charAt(0) != '0') ? 1 : 0; |
36 |
| - for (int i = 2; i <= s.length(); i++) { |
37 |
| - int first = Integer.valueOf(s.substring(i - 1, i)); |
38 |
| - int second = Integer.valueOf(s.substring(i - 2, i)); |
39 |
| - if (first > 0 && first <= 9) { |
40 |
| - dp[i] += dp[i - 1]; |
41 |
| - } |
42 |
| - if (second >= 10 && second <= 26) { |
43 |
| - dp[i] += dp[i - 2]; |
44 |
| - } |
| 14 | + public int numDecodings(String s) { |
| 15 | + if (s == null || s.length() == 0) { |
| 16 | + return 0; |
| 17 | + } |
| 18 | + int[] dp = new int[s.length() + 1]; |
| 19 | + dp[0] = 1; |
| 20 | + dp[1] = (s.charAt(0) != '0') ? 1 : 0; |
| 21 | + for (int i = 2; i <= s.length(); i++) { |
| 22 | + int first = Integer.valueOf(s.substring(i - 1, i)); |
| 23 | + int second = Integer.valueOf(s.substring(i - 2, i)); |
| 24 | + if (first > 0 && first <= 9) { |
| 25 | + dp[i] += dp[i - 1]; |
| 26 | + } |
| 27 | + if (second >= 10 && second <= 26) { |
| 28 | + dp[i] += dp[i - 2]; |
| 29 | + } |
| 30 | + } |
| 31 | + return dp[s.length()]; |
45 | 32 | }
|
46 |
| - return dp[s.length()]; |
47 |
| - } |
48 | 33 | }
|
49 | 34 | }
|
0 commit comments