File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -30,3 +30,35 @@ const countSubstrings = function(s) {
30
30
31
31
console . log ( countSubstrings ( "abc" ) ) ;
32
32
console . log ( countSubstrings ( "aaa" ) ) ;
33
+
34
+ // another
35
+
36
+ /**
37
+ * @param {string } s
38
+ * @return {number }
39
+ */
40
+ const countSubstrings = function ( s ) {
41
+ const arr = manachers ( s )
42
+ return arr . map ( e => ~ ~ ( ( e + 1 ) / 2 ) ) . reduce ( ( ac , e ) => ac + e , 0 )
43
+ } ;
44
+
45
+ function manachers ( s ) {
46
+ const str = `@#${ s . split ( '' ) . join ( '#' ) } #$`
47
+ const arr = Array ( str . length ) . fill ( 0 )
48
+
49
+ let center = right = 0
50
+ for ( let i = 1 , n = str . length ; i < n - 1 ; i ++ ) {
51
+ if ( i < right ) {
52
+ arr [ i ] = Math . min ( right - i , arr [ 2 * center - i ] )
53
+ }
54
+ while ( str [ i + arr [ i ] + 1 ] === str [ i - arr [ i ] - 1 ] ) {
55
+ arr [ i ] += 1
56
+ }
57
+ if ( i + arr [ i ] > right ) {
58
+ center = i
59
+ right = i + arr [ i ]
60
+ }
61
+ }
62
+
63
+ return arr
64
+ }
You can’t perform that action at this time.
0 commit comments