Skip to content

Commit fa6daef

Browse files
Shortest palindrome
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent e29e0fa commit fa6daef

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

214_shortest_palindrome/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test shortest_palindrome.c
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy