ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Apply Boyer–Moore Bad-Character Search
Learn how to apply boyer–moore bad-character search using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Index = 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
const unsigned char text[] = "ABAAABCD", pattern[] = "ABC";
int last[256], n = (int) strlen((const char *) text), m = (int) strlen((const char *) pattern);
for (int i = 0; i < 256; i++) last[i] = -1;
for (int i = 0; i < m; i++) last[pattern[i]] = i;
int shift = 0;
while (shift <= n - m) {
int index = m - 1;
while (index >= 0 && pattern[index] == text[shift + index]) index--;
if (index < 0) { printf("Index = %d\n", shift); break; }
int jump = index - last[text[shift + index]]; shift += jump > 1 ? jump : 1;
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Index = 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Compare from the pattern end and jump past a mismatched character's last occurrence.
- Display the computed result.
Compare from the pattern end and jump past a mismatched character's last occurrence.
EFFICIENCY
Time and space complexity
Time complexity
Average sublinear
Auxiliary space
O(alphabet)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
