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)