34
34
* String : ABABCABABABAB
35
35
*
36
36
* A B A B C A B A B A B A B
37
- * Read: ^ to ^ Continue matching until with Pattern[0:4]
38
- * Read: ^ try ^ Unable to match Pattern[4]. But since last two characters form a sub-pattern
39
- * Read: try matching until Pattern[0:3] by checking if Pattern[2] == 'C'.
40
- * Read: Turns out no. No previously identified sub-pattern with 'C'. Restart.
37
+ * Read: ^ to ^ Continue matching where possible, leading to Pattern[0:4] matched.
38
+ * unable to match Pattern[4]. But notice that last two characters of String[0:4]
39
+ * form a sub-pattern with Pattern[0:2] Maybe Pattern[2] == 'C' and we can 're-use' Pattern[0:2]
40
+ * Read: ^ try ^ by checking if Pattern[2] == 'C'
41
+ * Read: Turns out no. No previously identified sub-pattern with 'C'. Restart matching Pattern.
41
42
* Read: ^ to ^ Found complete match! But rather than restart, notice that last 4 characters
42
- * Read: form a prefix sub-pattern of Pattern, so,
43
+ * Read: form a prefix sub-pattern of Pattern, which is Pattern[0:4] = "ABAB", so,
43
44
* Read: ^ ^ Start matching from Pattern[4] and finally Pattern[5]
44
45
*/
45
46
public class KMP {
@@ -53,6 +54,7 @@ private static int[] getPrefixIndices(String pattern) {
53
54
int len = pattern .length ();
54
55
int [] prefixIndices = new int [len + 1 ];
55
56
prefixIndices [0 ] = -1 ;
57
+ prefixIndices [1 ] = 0 ; // 1st character has no prefix to match with
56
58
57
59
int currPrefixMatched = 0 ; // num of chars of prefix pattern currently matched
58
60
int pos = 2 ; // Starting from the 2nd character, recall 1-indexed
0 commit comments