I'm having trouble comprehending the KMP algorithm. I understand prefix-suffix and have written code to calculate the prefix-suffix table:
Code: Select all
private int[] calculatePrefSuffArray(String pattern) {
char patternArray[] = pattern.toCharArray();
int tab[] = new int[pattern.length()];
tab[0] = 0;
int t = tab[0];
for (int i = 1; i < pattern.length(); i++) { // t = tab[i-1]
while(t >0 && patternArray[i] != patternArray[t] ) {
t = tab[t-1];
}
if(patternArray[i] == patternArray[t]) t++;
tab[i] = t;
}
return tab;
}
This is the algorithm outlined in the scaler topics. But I'm not sure how to utilize it in KMP. Could you please explain it to me?