From d87496afee9f8d630e6b25369adea7dffe6c1ce1 Mon Sep 17 00:00:00 2001 From: HC-kang Date: Thu, 22 Aug 2024 15:16:52 +0900 Subject: [PATCH] feat: 91. Decode Ways --- decode-ways/HC-kang.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 decode-ways/HC-kang.ts diff --git a/decode-ways/HC-kang.ts b/decode-ways/HC-kang.ts new file mode 100644 index 000000000..7e835a321 --- /dev/null +++ b/decode-ways/HC-kang.ts @@ -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(); + + 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); +} \ No newline at end of file