Skip to content

Commit bd68fd6

Browse files
author
Jeongwon Na
committed
decode ways solution
1 parent a6f741b commit bd68fd6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

decode-ways/njngwn.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity: O(n), n: s.length()
2+
// Space Complexity: O(n), n: s.length()
3+
class Solution {
4+
public int numDecodings(String s) {
5+
if (s.length() == 0) { // edge case
6+
return 0;
7+
}
8+
9+
int length = s.length()+1;
10+
int[] cntArr = new int[length]; // using dynamic programming
11+
12+
// check the case i == 0, i == 1 first
13+
cntArr[0] = 1;
14+
if (s.charAt(0) != '0') {
15+
cntArr[1] = 1;
16+
}
17+
18+
for (int i = 2; i < length; ++i) {
19+
char ch = s.charAt(i-1);
20+
if (ch != '0') { // check for 1-9
21+
cntArr[i] += cntArr[i-1];
22+
}
23+
24+
// check for 10-26
25+
int num = (s.charAt(i-2)-'0') * 10 + (ch-'0');
26+
if (num >= 10 && num <= 26) {
27+
cntArr[i] += cntArr[i-2];
28+
}
29+
}
30+
31+
return cntArr[length-1];
32+
}
33+
}

0 commit comments

Comments
 (0)