The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).
More details can be found at the link: https://en.wikipedia.org/wiki/Substring#Border
e.g
abcdabc - border string is abc - length is 3
ababab - border string is abab - length is 4
C++ solution/ Algorithm for border string is as below.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int longestBorder(const string& s) {
int len = s.length();
vector<int> prefixFunc(len);
prefixFunc[0] = 0;
int curBorderLen = 0;
for (int i = 1; i < len; ++i) {
while (curBorderLen > 0 && s[curBorderLen] != s[i])
curBorderLen = prefixFunc[curBorderLen - 1];
if (s[curBorderLen] == s[i])
++curBorderLen;
prefixFunc[i] = curBorderLen;
}
return prefixFunc[len-1];
}
int main() {
string s;
cin >> s;
cout << longestBorder(s) << endl;
}
Time Complexity: O(n)
Ideone - https://ideone.com/UIjwSG



