Skip to content

Commit d87496a

Browse files
committed
feat: 91. Decode Ways
1 parent 9bc1fdc commit d87496a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

decode-ways/HC-kang.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// T.C: O(n)
2+
// S.C: O(n)
3+
function numDecodings(s: string): number {
4+
const NUM_OF_ALPHA = 26;
5+
const memo = new Map<number, number>();
6+
7+
function dfs(idx: number): number {
8+
if (idx === s.length) {
9+
return 1;
10+
}
11+
if (s[idx] === '0') {
12+
return 0;
13+
}
14+
if (memo.has(idx)) {
15+
return memo.get(idx)!;
16+
}
17+
18+
let count = dfs(idx + 1);
19+
if (
20+
idx + 2 <= s.length && // check if idx + 2 is in the range
21+
parseInt(s.slice(idx, idx + 2), 10) <= NUM_OF_ALPHA
22+
) {
23+
count += dfs(idx + 2);
24+
}
25+
26+
memo.set(idx, count);
27+
return count;
28+
}
29+
30+
return dfs(0);
31+
}

0 commit comments

Comments
 (0)