Boyer Moore algorithm is used for pattern searching inside a string. This is the 3rdalgorithm in this pattern search series.
This algorithm is very easy to understand. You need to remember below 3 points only.
- Given a string ‘s’ and pattern ‘p’ we start searching from right most element.
- When there is a mismatch occurred, one of below 2 rules to be followed:
- If the mismatch character is not in the pattern p, then we skip the whole word in the string s.
- If the mismatched character is present in pattern ‘p’, then we skip till the character in pattern ‘p’ matches a character in string ‘s’.
Don’t worry if you are not able to relate or visualize. We shall understand with help of an example.
Consider the string S = “prodeveloper” And pattern P = lope.
We start searching from right most character as highlighted in the image below
If there is mismatch and the character ‘d; from the string ‘s’ is not present in the pattern ‘p’, we shall skip till ‘d’. Hence in the next pass will look as below
Again there is a mismatch. But the letter ‘l’ from the string is present in the pattern ‘p’. Hence we skip till the letter ‘l’ from the string. Hence in the next pass will look like below:
Now again from right most, check ‘e’ from the pattern ‘p’ and string ‘s’. It is a match. Similarly we do it for ‘p’ ‘o’ ‘l’ all are match, Hence we got our result, and the substring is present in string s.
Implementation of Boyer Moore algorithm