File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -11,3 +11,42 @@ const shortestPalindrome = function(s) {
11
11
let suffix = s . substring ( j ) ;
12
12
return suffix . split ( '' ) . reverse ( ) . join ( '' ) + shortestPalindrome ( s . substring ( 0 , j ) ) + suffix ;
13
13
} ;
14
+
15
+ // another
16
+
17
+ /**
18
+ * @param {string } s
19
+ * @return {string }
20
+ */
21
+ const shortestPalindrome = function ( s ) {
22
+ const tmp = s + '#' + s . split ( '' ) . reverse ( ) . join ( '' )
23
+ const fail = getFail ( tmp )
24
+ return (
25
+ s
26
+ . split ( '' )
27
+ . slice ( fail [ fail . length - 1 ] )
28
+ . reverse ( )
29
+ . join ( '' ) + s
30
+ )
31
+ }
32
+
33
+ function getFail ( s ) {
34
+ const n = s . length
35
+ const table = new Array ( n ) . fill ( 0 )
36
+ let index = 0
37
+ for ( let i = 1 ; i < n ; ) {
38
+ if ( s . charAt ( index ) === s . charAt ( i ) ) {
39
+ table [ i ] = ++ index
40
+ i ++
41
+ } else {
42
+ if ( index > 0 ) {
43
+ index = table [ index - 1 ]
44
+ } else {
45
+ index = 0
46
+ i ++
47
+ }
48
+ }
49
+ }
50
+ return table
51
+ }
52
+
You can’t perform that action at this time.
0 commit comments