File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ var countSubstrings = function ( s ) {
2+ let result = 0 ;
3+ for ( let i = 0 ; i < s . length ; i ++ ) {
4+ let left = i ,
5+ right = i ; // odd length substrings
6+ helper ( s , left , right ) ;
7+
8+ ( left = i ) , ( right = i + 1 ) ; // even length substrings
9+ helper ( s , left , right ) ;
10+ }
11+ function helper ( s , l , r ) {
12+ // increment result and keep expanding left and right, while left and right indexes are within range and they're equal
13+ while ( l >= 0 && r <= s . length && s [ l ] === s [ r ] ) {
14+ result ++ ;
15+ l -- ;
16+ r ++ ;
17+ }
18+ }
19+ return result ;
20+ } ;
21+
22+ // test cases
23+ console . log ( countSubstrings ( "abc" ) ) ; // 3
24+ console . log ( countSubstrings ( "aaa" ) ) ; // 6
25+ console . log ( countSubstrings ( "a" ) ) ; // 1
26+ console . log ( countSubstrings ( "" ) ) ; // 0
27+
28+ // space - O(1) - constant variable `result`
29+ // time - O(n^2) - iterating through the string and expanding both ways
You can’t perform that action at this time.
0 commit comments