Skip to content

Commit 063a303

Browse files
committed
KMP: Improve docs
1 parent 51d3ad6 commit 063a303

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/algorithms/patternFinding/KMP.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,13 @@
3434
* String : ABABCABABABAB
3535
*
3636
* 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.
4142
* 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,
4344
* Read: ^ ^ Start matching from Pattern[4] and finally Pattern[5]
4445
*/
4546
public class KMP {
@@ -53,6 +54,7 @@ private static int[] getPrefixIndices(String pattern) {
5354
int len = pattern.length();
5455
int[] prefixIndices = new int[len + 1];
5556
prefixIndices[0] = -1;
57+
prefixIndices[1] = 0; // 1st character has no prefix to match with
5658

5759
int currPrefixMatched = 0; // num of chars of prefix pattern currently matched
5860
int pos = 2; // Starting from the 2nd character, recall 1-indexed

0 commit comments

Comments
 (0)