forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhyejjun.js
42 lines (33 loc) ยท 885 Bytes
/
hyejjun.js
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
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function (s) {
if (s == null || s.length === 0) {
return 0;
}
const n = s.length;
const dp = new Array(n + 1).fill(0);
dp[0] = 1;
dp[1] = s[0] === '0' ? 0 : 1;
for (let i = 2; i <= n; i++) {
const oneDigit = parseInt(s.substring(i - 1, i));
const twoDigits = parseInt(s.substring(i - 2, i));
// Check if single digit decoding is possible
if (oneDigit >= 1 && oneDigit <= 9) {
dp[i] += dp[i - 1];
}
// Check if two digit decoding is possible
if (twoDigits >= 10 && twoDigits <= 26) {
dp[i] += dp[i - 2];
}
}
return dp[n];
};
console.log(numDecodings("12"));
console.log(numDecodings("226"));
console.log(numDecodings("06"));
/*
์๊ฐ ๋ณต์ก๋: O(n)
๊ณต๊ฐ ๋ณต์ก๋: O(n)
*/