Skip to content

Commit 7ab5529

Browse files
committed
feat: add Palindromic Substrings
1 parent 227a43f commit 7ab5529

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ Roadmap: https://neetcode.io/roadmap
8484
| 198 | [House Robber](https://leetcode.com/problems/house-robber/description/) | Medium | [ts](./TypeScript/70.climbing-stairs.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 |
87+
| 647 | [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/description/) | Medium | [ts](./TypeScript/647.palindromic-substrings.ts) | 1-D DP |
8788

8889
### Others
8990

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// dp[i+1][j-1] === true && s[i] === s[j] => dp[i][j] === true
2+
function countSubstrings(s: string): number {
3+
let dp: boolean[][] = [];
4+
let count = 0;
5+
6+
for (let i = 0; i < s.length; i++) {
7+
dp[i] = [];
8+
dp[i][i] = true;
9+
count = count + 1;
10+
}
11+
12+
for (let i = s.length - 1; i >= 0; i--) {
13+
for (let j = i + 1; j < s.length; j++) {
14+
if (j - i === 1 || dp[i + 1][j - 1]) {
15+
dp[i][j] = s[i] === s[j];
16+
}
17+
18+
if (dp[i][j]) {
19+
count = count + 1;
20+
}
21+
}
22+
}
23+
24+
return count;
25+
}
26+
27+
console.log(countSubstrings("abc"));
28+
console.log(countSubstrings("aaa"));

0 commit comments

Comments
 (0)