Skip to content

Commit 34a18cd

Browse files
committed
5: palindromic-substrings
1 parent 718bde0 commit 34a18cd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function countSubstrings(s: string): number {
2+
// SC: O(N^2)
3+
const dict: Map<string, boolean> = new Map();
4+
const n = s.length;
5+
6+
// TC: O(N^2)
7+
for (let start = 0; start < n; start++) {
8+
for (let end = start; end >= 0; end--) {
9+
if (start === end) {
10+
dict.set(`${start}:${end}`, true);
11+
} else if (start + 1 === end) {
12+
dict.set(`${start}:${end}`, s[start] === s[end]);
13+
} else {
14+
const flag = s[start] === s[end];
15+
const mid = dict.get(`${start + 1}:${end - 1}`);
16+
dict.set(`${start}:${end}`, flag && mid);
17+
}
18+
}
19+
}
20+
21+
let cnt = 0;
22+
23+
// TC: O(N^2)
24+
// SC: O(1)
25+
for (const v of dict.values()) {
26+
if (v) {
27+
cnt++;
28+
}
29+
}
30+
31+
return cnt;
32+
}
33+
34+
// TC: O(N^2)
35+
// SC: O(N^2)

0 commit comments

Comments
 (0)