longest prefix which is also suffix

Solutions on MaxInterview for longest prefix which is also suffix by the best coders in the world

showing results for - "longest prefix which is also suffix"
Coby
20 Feb 2018
1// CPP program to find length of the longest 
2// prefix which is also suffix 
3#include <bits/stdc++.h> 
4using namespace std; 
5  
6// Function to find largest prefix which is also a suffix 
7int largest_prefix_suffix(const std::string &str) { 
8    
9  int n = str.length(); 
10    
11  if(n < 2) { 
12    return 0; 
13  } 
14  
15  int len = 0; 
16  int i = n/2; 
17    
18  while(i < n) { 
19    if(str[i] == str[len]) { 
20      ++len; 
21      ++i; 
22    } else { 
23      if(len == 0) { // no prefix 
24        ++i; 
25      } else { // search for shorter prefixes 
26        --len; 
27      } 
28    } 
29  } 
30    
31  return len; 
32  
33} 
34  
35// Driver code 
36int main() { 
37      
38string s = "blablabla"; 
39  
40cout << largest_prefix_suffix(s); 
41  
42return 0; 
43} 
44