Skip to content

Commit 9529512

Browse files
committed
5. decode-ways
1 parent 8f4e343 commit 9529512

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

โ€Ždecode-ways/whewchews.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function numDecodings(s: string): number {
2+
// SC: O(N)
3+
const memo: { [key: number]: number } = { [s.length]: 1 };
4+
5+
// TC: O(N)
6+
const dfs = (start: number): number => {
7+
if (start in memo) {
8+
return memo[start];
9+
}
10+
11+
if (s[start] === "0") {
12+
// 0์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ์šฐ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ์—†์Œ
13+
memo[start] = 0;
14+
} else if (
15+
start + 1 < s.length &&
16+
parseInt(s.substring(start, start + 2)) < 27
17+
) {
18+
// ๋‹ค์Œ์— ์˜ค๋Š” ๊ธ€์ž๊ฐ€ ๋‘๊ธ€์ž ์ด์ƒ ์žˆ๊ณ , start start+1 ๋‘๊ธ€์ž๊ฐ€ 1~26 ์‚ฌ์ด์˜ ๊ฐ’์ธ ๊ฒฝ์šฐ
19+
memo[start] = dfs(start + 1) + dfs(start + 2);
20+
} else {
21+
// 1๊ธ€์ž๋งŒ ๋‚จ์€ ๊ฒฝ์šฐ or ์ฒซ ๋‘๊ธ€์ž๊ฐ€ 27๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ
22+
memo[start] = dfs(start + 1);
23+
}
24+
25+
return memo[start];
26+
};
27+
28+
// SC: ์žฌ๊ท€ํ˜ธ์ถœ O(N)
29+
return dfs(0);
30+
}
31+
32+
// TC: O(N)
33+
// SC: O(N)

0 commit comments

Comments
ย (0)