|
1 | 1 |
|
| 2 | + /* * |
| 3 | + * The time complexity of KMP algorithm is O(n) in the worst case |
| 4 | + * Example use case: Pattern = AABCAB Text = AAABACABAABCABAABCA |
| 5 | + * LPSArray = [ 0, 0, 1, 2, 3, 0 ] |
| 6 | + * Found = true, at position 13 |
| 7 | + * */ |
| 8 | + |
2 | 9 | // Longest prefix suffix - generate an array of the longest previous suffix for each pattern array value
|
3 | 10 | const createLPS = (pattern, patternLength, lps) => {
|
4 | 11 | // initialise the current longest prefix suffix length and iterator index values
|
|
37 | 44 | * array/table to essentially skip chunks of the text that we know will match the pattern.
|
38 | 45 | * This algorithm will return true if the pattern is a subset of the text, else it will return false.
|
39 | 46 | * This algorithm accepts two strings, the pattern and text.
|
| 47 | + * The time complexity of the KMP algorithm is O(n) in the worst case. |
40 | 48 | * */
|
41 | 49 | const KMPSearch = (pattern, text) => {
|
42 | 50 | const patternLength = pattern.length; // Often referred to as M
|
43 | 51 | const textLength = text.length; // Often referred to as N
|
44 | 52 |
|
45 | 53 | let lps = [patternLength]; // Longest Pattern Suffix - array containing the lps for all pattern value positions
|
46 | 54 | lps = createLPS(pattern, patternLength, lps); // This is preprocessed - before the text is searched for the pattern.
|
| 55 | + // console.log({ lpsArray: lps }) |
47 | 56 |
|
48 | 57 | let patternIndex = 0; // Referred to as P
|
49 | 58 | let textIndex = 0; // Referred to as T
|
|
0 commit comments