File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test shortest_palindrome.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+ #include <string.h>
4+ #include <stdbool.h>
5+
6+ static inline char * rev_cpy (char * dst , char * src , int size )
7+ {
8+ while (size -- > 0 ) {
9+ * -- dst = * src ++ ;
10+ }
11+ return dst ;
12+ }
13+
14+ static char * shortestPalindrome (char * s )
15+ {
16+ int i , j , len = strlen (s );
17+ char * result = malloc (2 * len + 2 );
18+
19+ strcpy (result , s );
20+ result [len ] = '#' ;
21+ rev_cpy (result + 2 * len + 1 , s , len );
22+
23+ int res_len = 2 * len + 1 ;
24+ int * next = malloc (res_len * sizeof (int ));
25+ memset (next , 0 , res_len * sizeof (int ));
26+ for (i = 1 ; i < res_len ; i ++ ) {
27+ int j = next [i - 1 ];
28+ while (j > 0 && result [i ] != result [j ]) {
29+ j = next [j - 1 ];
30+ }
31+ j += result [i ] == result [j ];
32+ next [i ] = j ;
33+ }
34+
35+ memmove (result , result + len + 1 , len + 1 );
36+ int start = len - next [res_len - 1 ];
37+ strcpy (result + start , s );
38+ return result ;
39+ }
40+
41+ int main (int argc , char * * argv )
42+ {
43+ if (argc != 2 ) {
44+ fprintf (stderr , "Usage: ./test string\n" );
45+ exit (-1 );
46+ }
47+
48+ printf ("%s\n" , shortestPalindrome (argv [1 ]));
49+ return 0 ;
50+ }
You can’t perform that action at this time.
0 commit comments