Skip to content

Commit 4f38c55

Browse files
committed
solve: decode ways
1 parent a0ef72e commit 4f38c55

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

decode-ways/wogha95.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// TC: O(N)
2+
// SC: O(N)
3+
4+
/**
5+
* @param {string} s
6+
* @return {number}
7+
*/
8+
var numDecodings = function (s) {
9+
if (s[0] === "0") {
10+
return 0;
11+
}
12+
if (s.length === 1) {
13+
return 1;
14+
}
15+
16+
const dpTable = new Array(s.length).fill(0);
17+
if (s[0] !== "0") {
18+
dpTable[0] = 1;
19+
}
20+
if (s[1] !== "0") {
21+
dpTable[1] += 1;
22+
}
23+
if (isValid(`${s[0]}${s[1]}`)) {
24+
dpTable[1] += 1;
25+
}
26+
27+
for (let index = 2; index < s.length; index++) {
28+
if (s[index] !== "0") {
29+
dpTable[index] += dpTable[index - 1];
30+
}
31+
if (s[index - 1] !== "0" && isValid(`${s[index - 1]}${s[index]}`)) {
32+
dpTable[index] += dpTable[index - 2];
33+
}
34+
}
35+
36+
return dpTable[dpTable.length - 1];
37+
38+
function isValid(stringNumber) {
39+
const number = Number(stringNumber);
40+
if (number <= 0) {
41+
return false;
42+
}
43+
if (27 <= number) {
44+
return false;
45+
}
46+
return true;
47+
}
48+
};

0 commit comments

Comments
 (0)