The main function that builds the failure/prefix table in KMP as I have seen (in all online resources even in this answer_ is as follows:
int j = 0;
for (int i = 1; i < pattern.length(); i++) {
while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) {
j = failure[j - 1];
}
if (pattern.charAt(j) == pattern.charAt(i)) {
j++;
}
failure[i] = j;
}
I can't understand this part:
j = failure[j - 1];
Why don't we do j--
instead to go back the string? How do we know that it is correct to update j
using the failed table?