The largest border#1307

The largest border (Editorial)

Construct the prefix function for the string and store it in the array . If the length of is , then to solve the problem it is enough to print the value p[n - 1].

Algorithm implementation

Build the prefix function of the input string in the array .

string s;
vector<int> p;

The function MaxBorderArray computes the prefix function for the string .

vector<int> MaxBorderArray(string &s)
{
  vector<int> p(s.size()); // p[0] = 0
  for (int i = 1; i < s.size(); i++)
  {
    int j = p[i - 1];
    while ((j > 0) && (s[i] != s[j])) 
      j = p[j - 1];
    if (s[i] == s[j]) p[i] = j + 1; else p[i] = 0;
  }
  return p;
}

Build the prefix function for the string using the MaxBorderArray function.

cin >> s;
p = MaxBorderArray(s);

Print the length of the longest border of the string, which is stored in p[s.size() - 1].

printf("%d\n", p[s.size() - 1]);