Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
41 views2 pages

KMP Algorithm for Pattern Matching

The document describes the KMP string matching algorithm in two parts. The first part explains how the prefix function Π is computed for a pattern string p. The second part describes how the KMP matcher uses the prefix function Π along with the pattern p and text string S to find all occurrences of p within S by efficiently skipping already matched characters without re-checking them.

Uploaded by

Zahid Hasan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views2 pages

KMP Algorithm for Pattern Matching

The document describes the KMP string matching algorithm in two parts. The first part explains how the prefix function Π is computed for a pattern string p. The second part describes how the KMP matcher uses the prefix function Π along with the pattern p and text string S to find all occurrences of p within S by efficiently skipping already matched characters without re-checking them.

Uploaded by

Zahid Hasan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

The prefix function,

Following pseudocode computes the prefix fucnction, : Compute-Prefix-Function (p) 1 m length[p] //p pattern to be matched 2 [1] 0 3 k0 4 for q 2 to m 5 do while k > 0 and p[k+1] != p[q] 6 do k [k] 7 If p[k+1] = p[q] 8 then k k +1 9 [q] k 10 return

The KMP Matcher


The KMP Matcher, with pattern p, string S and prefix function as input, finds a match of p in S. Following pseudocode computes the matching component of KMP algorithm: KMP-Matcher(S,p) 1 n length[S] 2 m length[p] 3 Compute-Prefix-Function(p) 4q0 //number of characters matched 5 for i 1 to n //scan S from left to right 6 do while q > 0 and p[q+1] != S[i] 7 do q [q] //next character does not match 8 if p[q+1] = S[i] 9 then q q + 1 //next character matches 10 if q = m //is all of p matched? 11 then print Pattern occurs with shift i m 12 q [ q] // look for the next match Note: KMP finds every occurrence of a p in S. That is why KMP does not terminate in step 12, rather it searches remainder of S for any more occurrences of p.

You might also like