Skip to content

Commit e38f140

Browse files
update 91
1 parent 34f6fd6 commit e38f140

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/main/java/com/fishercoder/solutions/_91.java

+39
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.HashMap;
4+
import java.util.Map;
5+
36
public class _91 {
47
/**
58
* Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation
@@ -31,4 +34,40 @@ public int numDecodings(String s) {
3134
return dp[s.length()];
3235
}
3336
}
37+
38+
public static class Solution2 {
39+
/**credit: https://leetcode.com/problems/decode-ways/solution/
40+
* Approach 1: Recursive Approach with Memoization
41+
*
42+
* The actual code goes from the right most character to the left side to build out the dp cache map.
43+
* And this HashMap uses index as its key instead of a substring.
44+
* */
45+
46+
public int numDecodings(String s) {
47+
return dp(new HashMap<>(), s, 0);
48+
}
49+
50+
private int dp(Map<Integer, Integer> cache, String s, int index) {
51+
if (cache.containsKey(index)) {
52+
return cache.get(index);
53+
}
54+
if (index == s.length()) {
55+
//this means we reached the end of the string, so return 1 as success
56+
return 1;
57+
}
58+
if (s.charAt(index) == '0') {
59+
//this means this string cannot be decoded
60+
return 0;
61+
}
62+
if (index == s.length() - 1) {
63+
return 1;
64+
}
65+
int ways = dp(cache, s, index + 1);
66+
if (Integer.parseInt(s.substring(index, index + 2)) <= 26) {
67+
ways += dp(cache, s, index + 2);
68+
}
69+
cache.put(index, ways);
70+
return cache.get(index);
71+
}
72+
}
3473
}

src/test/java/com/fishercoder/_91Test.java

+9
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,24 @@
88

99
public class _91Test {
1010
private static _91.Solution1 solution1;
11+
private static _91.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _91.Solution1();
16+
solution2 = new _91.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals(2, solution1.numDecodings("12"));
22+
assertEquals(2, solution2.numDecodings("12"));
23+
}
24+
25+
@Test
26+
public void test2() {
27+
assertEquals(1, solution1.numDecodings("10"));
28+
assertEquals(1, solution2.numDecodings("10"));
2029
}
2130

2231
}

0 commit comments

Comments
 (0)