Skip to content

Commit 32c4b56

Browse files
committed
feat: 647. Palindromic Substrings
1 parent 43853fc commit 32c4b56

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Time complexity: O(n^2)
2+
// Space complexity: O(n^2)
3+
4+
/**
5+
* @param {string} s
6+
* @return {number}
7+
*/
8+
var countSubstrings = function (s) {
9+
const n = s.length;
10+
const dp = Array.from({ length: n }, () =>
11+
Array.from({ length: n }, () => false)
12+
);
13+
14+
for (let end = 0; end < n; end++) {
15+
for (let start = end; start >= 0; start--) {
16+
if (start === end) {
17+
dp[start][end] = true;
18+
continue;
19+
}
20+
21+
if (start + 1 === end) {
22+
if (s[start] === s[end]) {
23+
dp[start][end] = true;
24+
}
25+
continue;
26+
}
27+
28+
if (s[start] === s[end] && dp[start + 1][end - 1]) {
29+
dp[start][end] = true;
30+
continue;
31+
}
32+
}
33+
}
34+
35+
let answer = 0;
36+
37+
for (let i = 0; i < n; i++) {
38+
for (let j = 0; j < n; j++) {
39+
if (dp[i][j]) {
40+
answer++;
41+
}
42+
}
43+
}
44+
45+
return answer;
46+
};

0 commit comments

Comments
 (0)