DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Updated on

The Knuth-Morris-Pratt (KMP)Algorithm - Implement strStr()

const allPointers = [];
var strStr = function (haystack, needle) {
  if (needle === "") return 0;
  const prefixTable = lpsTable(needle);
  let i = 0;
  let j = 0;
  while (i < haystack.length) {
    if (haystack[i] === needle[j]) {
      i += 1;
      j += 1;
    }
    if (j === needle.length) {
      allPointers.push(i - j);
      j = prefixTable[j - 1];
    } else if (i < haystack.length && haystack[i] !== needle[j]) {
      if (j > 0) {
        j = prefixTable[j - 1];
      } else {
        i += 1;
      }
    }
  }
};

console.log(allPointers);
Enter fullscreen mode Exit fullscreen mode

Longest Common Prefix

var lpsTable = function(word){
const patternTable = [0];
    let prefixIndex = 0;
    let suffixIndex = 1;

    while (suffixIndex < word.length) {
      if (word[prefixIndex] === word[suffixIndex]) {
        patternTable[suffixIndex] = prefixIndex + 1;
        suffixIndex += 1;
        prefixIndex += 1;
      } else if (prefixIndex === 0) {
        patternTable[suffixIndex] = 0;
        suffixIndex += 1;
      } else {
        prefixIndex = patternTable[prefixIndex - 1];
      }
    }

    return patternTable;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)