-
Notifications
You must be signed in to change notification settings - Fork 0
/
10453 - Make Palindrome.cpp
69 lines (62 loc) · 1.23 KB
/
10453 - Make Palindrome.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<cstring>
#include<bits/stdc++.h>
#define maxN 1100
using namespace std;
char text[maxN], pattern[maxN];
int f[maxN], length, index;
void computeFailureFunction()
{
int i = 1, j = 0;
f[0] = 0;
while(i < length)
{
if(pattern[i] == pattern[j])
{
j++;
f[i] = j;
i++;
}
else if(j > 0)
j = f[j-1];
else
{
f[i] = 0;
i++;
}
}
}
void kmpSearch()
{
computeFailureFunction();
int i = 0, j = 0;
while(i < length)
{
if(text[i] == pattern[j])
{
i++;
j++;
index = j;
}
else if(j > 0)
j = f[j-1];
else
i++;
}
}
int main()
{
while(gets(text))
{
memset(f, 0, sizeof f);
length = strlen(text);
for(int i = 0, j = length - 1; i < length; i++, j--)
pattern[i] = text[j];
index = 0;
kmpSearch();
printf("%d %s", length - index, text);
for(int i = index; i < length; i++)
printf("%c", pattern[i]);
puts("");
}
return 0;
}