Daa 9
Daa 9
Experiment 9
3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)
while (i < m) {
if (P[i] == P[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1]; // use previous lps
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"
cout << "--------------------------------------------\n";
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
while (i < n) {
if (P[j] == S[i]) {
i++;
j++;
}
if (j == m) {
found = true;
cout << ">> Pattern found at index: " << (i - j) << " <<\n";
j = lps[j - 1]; // get the index from LPS array
} else if (i < n && P[j] != S[i]) {
if (j != 0) {
j = lps[j - 1]; // use the LPS array
} else {
i++;
}
}
}
if (!found) {
cout << ">> No occurrences of the pattern found. <<\n";
}
int main() {
string S = "ababcababcababc";
string P = "ababc";
KMPsearch(S, P);
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
5. Output:
7. Learning Outcomes:
1. Efficient String Matching:
You will understand how the KMP algorithm efficiently finds all occurrenc
of a pattern P in a string S, avoiding redundant comparisons.
2. LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix Suffix (LPS)
array to skip unnecessary comparisons, optimizing the search process.
3. Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and space
complexity, understanding why KMP achieves linear time complexity O(n
m) with only O(m) space overhead.