Skip to content

Commit

Permalink
feat: 91. Decode Ways
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Aug 22, 2024
1 parent 9bc1fdc commit d87496a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions decode-ways/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// T.C: O(n)
// S.C: O(n)
function numDecodings(s: string): number {
const NUM_OF_ALPHA = 26;
const memo = new Map<number, number>();

function dfs(idx: number): number {
if (idx === s.length) {
return 1;
}
if (s[idx] === '0') {
return 0;
}
if (memo.has(idx)) {
return memo.get(idx)!;
}

let count = dfs(idx + 1);
if (
idx + 2 <= s.length && // check if idx + 2 is in the range
parseInt(s.slice(idx, idx + 2), 10) <= NUM_OF_ALPHA
) {
count += dfs(idx + 2);
}

memo.set(idx, count);
return count;
}

return dfs(0);
}

0 comments on commit d87496a

Please sign in to comment.