File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments