The LPS (Longest Proper Prefix which is also a Suffix) algorithm goes as follows:
public static int[] constructLPSArray(String s) {
int n = s.length();
int[] arr = new int[n];
int j = 0;
for (int i = 1; i < n; ) {
if (s.charAt(i) == s.charAt(j)) {
arr[i] = j + 1;
i++;
j++;
} else {
if (j != 0) {
j = arr[j - 1];
} else {
i++;
}
}
}
return arr;
}
The if (s.charAt(i) == s.charAt(j))
part looks clear, but the else
part is unclear.
Why do we do:
if (j != 0) {
j = arr[j - 1];
} else {
i++;
}
More specifically, why does j = arr[j - 1]
work ? Or why do we even do it? How do we validate the correctness of this step?