UNPKG

lgrthms

Version:

Algorithms and data structures for your JavaScript and TypeScript projects 🧑‍💻

48 lines (47 loc) 1.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.knuthMorrisPratt = void 0; // O(n + m) time | O(m) space — where // n is the length of the string // m is the length of the substring function knuthMorrisPratt(string, substring) { const pattern = buildPattern(substring); let i = 0; let j = 0; while (i + substring.length - j <= string.length) { if (string[i] === substring[j]) { if (j === substring.length - 1) { return true; } i++; j++; } else if (j > 0) { j = pattern[j - 1] + 1; } else { i++; } } return false; } exports.knuthMorrisPratt = knuthMorrisPratt; function buildPattern(substring) { const pattern = new Array(substring.length).fill(-1); let j = 0; let i = 1; while (i < substring.length) { if (substring[i] === substring[j]) { pattern[i] = j; i++; j++; } else if (j > 0) { j = pattern[j - 1] + 1; } else { i++; } } return pattern; }