Skip to content

Commit

Permalink
5. decode-ways
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Aug 23, 2024
1 parent 8f4e343 commit 9529512
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions decode-ways/whewchews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
function numDecodings(s: string): number {
// SC: O(N)
const memo: { [key: number]: number } = { [s.length]: 1 };

// TC: O(N)
const dfs = (start: number): number => {
if (start in memo) {
return memo[start];
}

if (s[start] === "0") {
// 0으둜 μ‹œμž‘ν•˜λŠ” 경우 κ°€λŠ₯ν•œ 경우의 μˆ˜κ°€ μ—†μŒ
memo[start] = 0;
} else if (
start + 1 < s.length &&
parseInt(s.substring(start, start + 2)) < 27
) {
// λ‹€μŒμ— μ˜€λŠ” κΈ€μžκ°€ λ‘κΈ€μž 이상 있고, start start+1 λ‘κΈ€μžκ°€ 1~26 μ‚¬μ΄μ˜ 값인 경우
memo[start] = dfs(start + 1) + dfs(start + 2);
} else {
// 1κΈ€μžλ§Œ 남은 경우 or 첫 λ‘κΈ€μžκ°€ 27보닀 큰 경우
memo[start] = dfs(start + 1);
}

return memo[start];
};

// SC: μž¬κ·€ν˜ΈμΆœ O(N)
return dfs(0);
}

// TC: O(N)
// SC: O(N)

0 comments on commit 9529512

Please sign in to comment.