Rabin-Karp
The Rabin-Karp algorithm is a string searching algorithm that efficiently finds patterns within a text using hashing.
It's particularly useful when you need to find multiple patterns in a single text.
Here's an overview of how it works:
Hashing: The algorithm uses a hash function to generate a hash value for each substring of the text and the pattern to be searched.
Comparing Hashes: It compares the hash values of the pattern and each substring of the text. If the hash values match, it performs a full comparison of the substring and the pattern to confirm the match.
Rolling Hash: Instead of recalculating the hash for each substring, it uses a rolling hash function to efficiently update the hash value as it moves through the text.
pseudocode:
In this example, the rabinKarp
function takes the text
and pattern
as inputs and iterates through the text to find occurrences of the pattern.
It uses the hash
function to calculate the hash values for the pattern and substrings of the text, and recalculateHash
function to update the hash value as it moves through the text.
Finally, it prints the indices where the pattern is found.
Last updated