Skip to content

Commit ccc8d0d

Browse files
refactor 91
1 parent b52ac60 commit ccc8d0d

File tree

1 file changed

+22
-37
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-37
lines changed
Lines changed: 22 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,34 @@
11
package com.fishercoder.solutions;
22

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-
*/
193
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
216
* I used a dp array of size n + 1 to save subproblem solutions.
227
* dp[0] means an empty string will have one way to decode,
238
* dp[1] means the way to decode a string of size 1.
24-
*
259
* 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+
*/
2712

2813
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()];
4532
}
46-
return dp[s.length()];
47-
}
4833
}
4934
}

0 commit comments

Comments
 (0)