Skip to content

Commit e9acb59

Browse files
committed
Solution for Decode Ways #268
1 parent 9608bb4 commit e9acb59

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

decode-ways/dohyeon2.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
// TC : O(n)
3+
// SC : O(1)
4+
public int numDecodings(String s) {
5+
// If it starts with 0, the value can't be decoded.
6+
if (s.charAt(0) == '0') {
7+
return 0;
8+
}
9+
10+
int n = s.length();
11+
12+
int prev2 = 1;
13+
int prev1 = 1;
14+
15+
// dp[i] = dp[i-1] + dp[i-2]
16+
for (int i = 1; i < n; i++) {
17+
int current = 0;
18+
19+
if (s.charAt(i) != '0') {
20+
current += prev1;
21+
}
22+
23+
int twoDigit = Integer.valueOf(s.substring(i - 1, i + 1));
24+
25+
if (twoDigit >= 10 && twoDigit <= 26) {
26+
current += prev2;
27+
}
28+
29+
prev2 = prev1;
30+
prev1 = current;
31+
}
32+
33+
return prev1;
34+
}
35+
}

0 commit comments

Comments
 (0)