Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite38f140

Browse files
update 91
1 parent34f6fd6 commite38f140

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
packagecom.fishercoder.solutions;
22

3+
importjava.util.HashMap;
4+
importjava.util.Map;
5+
36
publicclass_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
returndp[s.length()];
3235
}
3336
}
37+
38+
publicstaticclassSolution2 {
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+
publicintnumDecodings(Strings) {
47+
returndp(newHashMap<>(),s,0);
48+
}
49+
50+
privateintdp(Map<Integer,Integer>cache,Strings,intindex) {
51+
if (cache.containsKey(index)) {
52+
returncache.get(index);
53+
}
54+
if (index ==s.length()) {
55+
//this means we reached the end of the string, so return 1 as success
56+
return1;
57+
}
58+
if (s.charAt(index) =='0') {
59+
//this means this string cannot be decoded
60+
return0;
61+
}
62+
if (index ==s.length() -1) {
63+
return1;
64+
}
65+
intways =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+
returncache.get(index);
71+
}
72+
}
3473
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,24 @@
88

99
publicclass_91Test {
1010
privatestatic_91.Solution1solution1;
11+
privatestatic_91.Solution2solution2;
1112

1213
@BeforeClass
1314
publicstaticvoidsetup() {
1415
solution1 =new_91.Solution1();
16+
solution2 =new_91.Solution2();
1517
}
1618

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

2231
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp