forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_prefix_suffix.cpp
74 lines (63 loc) · 1.52 KB
/
longest_prefix_suffix.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
70
71
72
73
74
/*
-LONGEST PREFIX SUFFIX
-Given a string, find the length of longest substring that is both prefix and suffix
-overlapping of prefix and suffix not allowed
-idea is to divide the given string from between and check if both string are equal
-if so return the length of that substring
-otherwise check for the shorter length
*/
#include <iostream>
using namespace std;
int main()
{
string s;
// input from the user
cin>>s;
/*if length of given string is less
than two, no such substring exist
hence prints 0*/
if (s.length()<2)
cout<<0;
else
{
/*divide string into two equal parts
and store starting indices of both*/
int l=0, i=s.length()/2;
/*loop calculating the length of
such substring*/
while (i<s.length())
{
/*check if left string character is equal
to right one if so increament indices of both
by 1*/
if (s[i]==s[l])
{
++l;
++i;
}
/*otherwise check for shoter substring*/
else
{
i=i-l+1;
l=0;
}
}
/*as overlapping is not allowed*/
if (l>s.length()/2)
cout<<s.length()/2;
else
cout<<l;
}
return 0;
}
/*
Test Cases
Test Case-1
Input = "rrrrr"
Output = 2
Test Case-2
Input = "abcdabc"
Output = 3
Time complexity = O(n), where n is length of string,i.e n=s.length()
Space complexity = O(1)
*/