Skip to content

Commit 1654d1d

Browse files
committed
feat: solve decode ways
1 parent 79a9c93 commit 1654d1d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

decode-ways/GangBean.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public int numDecodings(String s) {
3+
/**
4+
1. understanding
5+
- number to upper case alphabet mapping code: 1 -> A, ... 26 -> Z
6+
- many ways to decode each input string
7+
- also there can be no way to decode input string.
8+
- answer fits in 32-bit integer.
9+
10+
2. example
11+
- 12: (1, 2), (12)
12+
- 226: (2, 2, 6), (2, 26), (22, 6)
13+
- 06: (0, x)
14+
15+
3. strategy
16+
- iterate in reverse order,
17+
- at index k, dp[k] means the count of decode ways till that index.
18+
- dp[k-1] = 0 if num[k] == 0
19+
- dp[k-1] = dp[k] + dp[k+1] if 1<= nums[k-1:k] < 27
20+
- dp[k-1] = dp[k]
21+
- dp[n] = 1 -> assume that first empty input can be decoded in 1 way.
22+
23+
4. complexity
24+
- time: O(N)
25+
- space: O(1)
26+
*/
27+
int prev = 1;
28+
int current = 1;
29+
for (int i = s.length()-1; i >= 0; i--) { // O(1)
30+
if (s.charAt(i) == '0') {
31+
int tmp = current;
32+
current = 0;
33+
prev = tmp;
34+
} else if ( (i+1) < s.length() && Integer.parseInt(s.substring(i, i+2)) < 27) {
35+
int tmp = current;
36+
current = prev + current;
37+
prev = tmp;
38+
} else {
39+
prev = current;
40+
}
41+
}
42+
return current;
43+
}
44+
}
45+

0 commit comments

Comments
 (0)