20BCS5977 - DAA LAB WORKSHEET 3.3pdf
20BCS5977 - DAA LAB WORKSHEET 3.3pdf
1. Aim:
2. Task to be done:
How to use lps[] to decide next positions (or to know a number of characters to be
skipped)?
4. We know that characters pat[0..j-1] match with txt[i-j…i-1] (Note that j starts with 0
and increment it only when there is a match).
5. We also know (from above definition) that lps[j-1] is count of characters of pat[0…j-1]
that are both proper prefix and suffix.
6. From above two points, we can conclude that we do not need to match these lps[j-1]
characters with txt[i-j…i-1] because we know that these characters will anyway match. Let
us consider above example to understand this.
Code:
#include <bits/stdc++.h>
if (j == M) {
printf("Found pattern at index %d ", i - j);
j = lps[j - 1];
}
5. Result: