I found similar questions on StackOverflow, but my question is different.
Given a string s
contains lowercase alphabet
. I want to find the
This is similar to Z-algorithm for pattern matching. Except for the first case where len(LCP(s(1, 6), s)) = len (s).
We need to create a Z array . For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself.
Visualize the algorithm here : https://personal.utdallas.edu/~besp/demo/John2010/z-algorithm.htm
Below is the solution of the same :
public static int[] computeZ(String s) {
int l = 0; r = 0;
int [] Z = new int[len];
int len = s.length();
for (int k =0 ; k < len; k++ ) {
int j;
if (k < r) {
j = (z[k-l] < (r-k)) ? z[k-l] : (r-k)
} else {
j = 0;
}
while (k + j < len) {
if (s.charAt(k+j) == s.charAt(j)) {
j++;
} else {
break;
}
}
if (k + j > r) {
l = k;
r = k + j;
}
}
Z[0] = len;
return Z;
}
As mentioned by Aditya, this can be solved using Z-Algorithm. Please find the detailed explanation with implementation here - https://www.hackerearth.com/practice/algorithms/string-algorithm/z-algorithm/tutorial/