Skip to content

Commit 1494dd5

Browse files
committed
feat: add Decode Ways
1 parent 7ab5529 commit 1494dd5

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@ Roadmap: https://neetcode.io/roadmap
8181
| 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) | Medium | [ts](./TypeScript/17.letter-combinations-of-a-phone-number.ts) | Backtracking |
8282
| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/description/) | Easy | [ts](./TypeScript/70.climbing-stairs.ts) | 1-D DP |
8383
| 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/description/) | Easy | [ts](./TypeScript/70.climbing-stairs.ts) | 1-D DP |
84-
| 198 | [House Robber](https://leetcode.com/problems/house-robber/description/) | Medium | [ts](./TypeScript/70.climbing-stairs.ts) | 1-D DP |
84+
| 198 | [House Robber](https://leetcode.com/problems/house-robber/description/) | Medium | [ts](./TypeScript/198.house-robber.ts) | 1-D DP |
8585
| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/description/) | Medium | [ts](./TypeScript/213.house-robber-ii.ts) | 1-D DP |
8686
| 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/) | Medium | [ts](./TypeScript/5.longest-palindromic-substring.ts) | 1-D DP |
8787
| 647 | [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/description/) | Medium | [ts](./TypeScript/647.palindromic-substrings.ts) | 1-D DP |
88+
| 91 | [Decode Ways](https://leetcode.com/problems/decode-ways/description/) | Medium | [ts](./TypeScript/91.decode-ways.ts) | 1-D DP |
8889

8990
### Others
9091

TypeScript/91.decode-ways.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// dp [i] = dp[i+1] + dp[i+2]
2+
function numDecodings(s: string): number {
3+
const dp = { [s.length]: 1 };
4+
5+
for (let i = s.length - 1; i >= 0; i--) {
6+
if (s[i] === "0") {
7+
dp[i] = 0;
8+
} else {
9+
dp[i] = dp[i + 1];
10+
}
11+
12+
if (
13+
i + 1 < s.length &&
14+
(s[i] === "1" || (s[i] === "2" && "0123456".includes(s[i + 1])))
15+
) {
16+
dp[i] = dp[i] + dp[i + 2];
17+
}
18+
}
19+
20+
return dp[0];
21+
}
22+
23+
console.log(numDecodings("226"));
24+
console.log(numDecodings("106"));

0 commit comments

Comments
 (0)