Skip to content

Commit e7901f7

Browse files
committed
Add palindromic-substrings solution
1 parent 2836f79 commit e7901f7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

palindromic-substrings/Jeehay28.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
6+
// TC : O(n^2)
7+
// SC : O(1)
8+
9+
var countSubstrings = function (s) {
10+
// For each character in the string, treat it as the center of a potential palindrome.
11+
12+
// 'Count Palindromic Substrings' helper function
13+
const countPS = (left, right) => {
14+
let cnt = 0;
15+
while (left >= 0 && right < s.length && s[left] === s[right]) {
16+
cnt += 1;
17+
left -= 1;
18+
right += 1;
19+
}
20+
return cnt;
21+
};
22+
23+
let totCnt = 0;
24+
25+
for (let i = 0; i < s.length; i++) {
26+
// left === right : 1 center point, odd-length palindromic
27+
totCnt += countPS(i, i);
28+
29+
// left !== right : 2 center points, even-length palindromic
30+
totCnt += countPS(i, i + 1);
31+
}
32+
33+
return totCnt;
34+
};
35+
36+
37+

0 commit comments

Comments
 (0)