-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPrefixSuffix.cpp
More file actions
69 lines (61 loc) · 1000 Bytes
/
LongestPrefixSuffix.cpp
File metadata and controls
69 lines (61 loc) · 1000 Bytes
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
Given a string of character, find the length of longest proper prefix which is also a proper suffix.
Example:
S = abab
lps is 2 because, ab.. is prefix and ..ab is also a suffix.
Input:
First line is T number of test cases. 1<=T<=100.
Each test case has one line denoting the string of length less than 100000.
Expected time compexity is O(N).
Output:
Print length of longest proper prefix which is also a proper suffix.
Example:
Input:
2
abab
aaaa
Output:
2
2
#include <bits/stdc++.h>
using namespace std;
int lps (string);
int main ()
{
int T;
cin >> T;
getchar ();
while (T--)
{
string s;
cin >> s;
printf ("%d \n ", lps (s));
}
return 0;
}
int lps (string s)
{
int n = s.size ();
int lps[n];
int i = 1, j = 0;
lps[0] = 0;
while (i < n)
{
if (s[i] == s[j])
{
j++;
lps[i] = j;
i++;
}
else
{
if (j != 0)
j = lps[j - 1];
else
{
lps[i] = 0;
i++;
}
}
}
return lps[n - 1];
}