menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

Knuth Morr...
source image

Prodevelopertutorial

2w

read

427

img
dot

Image Credit: Prodevelopertutorial

Knuth Morris Pratt String matching algorithm

  • Given a string “s” and a pattern ‘p’, the task is to find if the pattern is present in the string “s”.
  • A brute force approach compares one letter after another, till we find the sub pattern or we reach end of the string.
  • There are 3 pattern matching algorithms, Knuth Morris Pratt(KMP) is the first algorithm in them.
  • KMP Algorithm is bit difficult to understand, and has 2 parts: partial match table and string matching.
  • We create a partial match table which will help us to skip the number of characters when there is a mismatch, eliminating checking of all the characters one by one.
  • To search the string, take 2 variables, i.e., i = string [str[0]] & j = pattern[0].
  • If the match is found, increment the index of both I and j. If there is a mismatch, move j to the location in PMT. If j = 0, then increment i index.
  • KMP Algorithm follows a high-level working approach to find the sub-pattern in a given string using the partial match table.
  • C++ implementation of KMP Algorithm which creates a partial match table based on the pattern and runs the KMP algorithm pattern p on target t, returns a Boolean if or not in the target.
  • KMP Algorithm is a more efficient way to search the pattern in the target in comparison to the brute-force approach.

Read Full Article

like

25 Likes

For uninterrupted reading, download the app