-
Notifications
You must be signed in to change notification settings - Fork 387
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #752 from stlouisp/sd2
CPP program to find length of the longest prefix which is also suffix
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
Advanced data structures/Longest prefix which is also suffix.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |