-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path91.decode-ways.java
More file actions
50 lines (38 loc) · 1.08 KB
/
Copy path91.decode-ways.java
File metadata and controls
50 lines (38 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
* @lc app=leetcode id=91 lang=java
*
* [91] Decode Ways
*/
// @lc code=start
class Solution {
Map<Integer, Integer> memo = new HashMap<>();
public int numDecodings(String s) {
return recursiveWithMemo(0, s);
}
private int recursiveWithMemo(int index, String str) {
// Have we already seen this substring?
if (memo.containsKey(index)) {
return memo.get(index);
}
// If you reach the end of the string
// Return 1 for success.
if (index == str.length()) {
return 1;
}
// If the string starts with a zero, it can't be decoded
if (str.charAt(index) == '0') {
return 0;
}
if (index == str.length() - 1) {
return 1;
}
int ans = recursiveWithMemo(index + 1, str);
if (Integer.parseInt(str.substring(index, index + 2)) <= 26) {
ans += recursiveWithMemo(index + 2, str);
}
// Save for memoization
memo.put(index, ans);
return ans;
}
}
// @lc code=end