Skip to content

Commit c67f669

Browse files
committed
Num Decodings
1 parent d6b6770 commit c67f669

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

decode-ways/hyejjun.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
6+
var numDecodings = function (s) {
7+
if (s == null || s.length === 0) {
8+
return 0;
9+
}
10+
11+
const n = s.length;
12+
const dp = new Array(n + 1).fill(0);
13+
dp[0] = 1;
14+
dp[1] = s[0] === '0' ? 0 : 1;
15+
16+
for (let i = 2; i <= n; i++) {
17+
const oneDigit = parseInt(s.substring(i - 1, i));
18+
const twoDigits = parseInt(s.substring(i - 2, i));
19+
20+
// Check if single digit decoding is possible
21+
if (oneDigit >= 1 && oneDigit <= 9) {
22+
dp[i] += dp[i - 1];
23+
}
24+
25+
// Check if two digit decoding is possible
26+
if (twoDigits >= 10 && twoDigits <= 26) {
27+
dp[i] += dp[i - 2];
28+
}
29+
}
30+
31+
return dp[n];
32+
};
33+
34+
35+
console.log(numDecodings("12"));
36+
console.log(numDecodings("226"));
37+
console.log(numDecodings("06"));
38+
39+
/*
40+
시간 복잡도: O(n)
41+
공간 복잡도: O(n)
42+
*/

0 commit comments

Comments
 (0)