KMP String Matching Algorithm
KMP String Matching Algorithm
KMP String Matching Algorithm
String a b c d e f g h String a b c d e f g h
Pattern d e f Pattern d e f
Not Match, Shift by one Not Match, Shift by one
String a b c d e f g h String a b c d e f g h
Pattern d e f Pattern d e f
Not Match, Shift by one Match, Compare Next
String a b c d e f g h String a b c d e f g h
Pattern d e f Pattern d e f
Not Match, Shift by one Match, Shift by one
String a b c d e f g h
Pattern d e f
Pattern Matched, Return the position
Next example
i
String: a b c d a b c a b c d f
Pattern a b c d f
j
If character at i and j position Not matched,
move j to 1st of position of Pattern and count the total no of character move
i back by j
String: a b c d a b c a b c d f
Now move back i to the total no of character counted by j and move next by 1.
Pattern a b c d f do the same process.
j
i
String: a b c d a b c a b c d f
Here Count = 4
Pattern a b c d f
j
i
String: a b c d a b c a b c d f i
Pattern a b c d f Not Matched String: a b c d a b c a b c d f
j Pattern a b c d f Matched
j
i i
String: a b c d a b c a b c d f String: a b c d a b c a b c d f
Pattern a b c d f Not Matched Pattern a b c d f Matched
j j
Here count = 3
i
String: a b c d a b c a b c d f
Pattern a b c d f
j
a b c d a b e a b f
0 0 0 0 1 2 0 1 2 0
a a b c a d a a b e
0 1 0 0 1 0 1 2 0 0
a b c d e a b f a b c
0 0 0 0 0 1 2 0 1 2 3
i
Compare s[i] with p[j+1]
a b a b c a b c a b a b a b d
If match – increase i and j by 1 j
0 1 2 3 4 5
Else if not matched a b a b d
Pattern
Move back j to their Π table value
if table value is 0 than increase i by 1 Π Table 0 0 1 2 0
Π Table 0 0 1 2 0