Skip to content

Commit

Permalink
Merge pull request #752 from stlouisp/sd2
Browse files Browse the repository at this point in the history
 CPP program to find length of the longest prefix which is also suffix
  • Loading branch information
tanus786 authored Oct 29, 2022
2 parents 2a775d6 + 28c409e commit 708bcd8
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Advanced data structures/Longest prefix which is also suffix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// CPP program to find length of the
// longest prefix which is also suffix
#include <bits/stdc++.h>
using namespace std;

// Function to find largest prefix
// which is also a suffix
int largest_prefix_suffix(const std::string
&str)
{

int n = str.length();

// if n is less than 2
if(n < 2) {
return 0;
}

int len = 0;
int i = 1;

// Iterate i till n
while(i < n)
{

// If str[i] is equal to
// str[len]
if(str[i] == str[len])
{
++len;
++i;
}
else
{
i = i - len + 1;
len = 0;
}
}

// Return len
return len>n/2? len/2:len;

}

// Driver code
int main()
{

string s = "blablabla";

// Function Call
cout << largest_prefix_suffix(s);
return 0;
}

0 comments on commit 708bcd8

Please sign in to comment.