Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Rabin–Karp algorithm
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Multiple pattern search == The Rabin–Karp algorithm is inferior for single pattern searching to [[Knuth–Morris–Pratt algorithm]], [[Boyer–Moore string-search algorithm]] and other faster single pattern [[string searching algorithm]]s because of its slow worst case behavior. However, it is a useful algorithm for [[String searching algorithm#Algorithms using a finite set of patterns|multiple pattern search]]. To find any of a large number, say ''k'', fixed length patterns in a text, a simple variant of the Rabin–Karp algorithm uses a [[Bloom filter]] or a [[set data structure]] to check whether the hash of a given string belongs to a set of hash values of patterns we are looking for: <syntaxhighlight lang="php" line> function RabinKarpSet(string s[1..n], set of string subs, m): set hsubs := emptySet foreach sub in subs insert hash(sub[1..m]) into hsubs hs := hash(s[1..m]) for i from 1 to n-m+1 if hs ∈ hsubs and s[i..i+m-1] ∈ subs return i hs := hash(s[i+1..i+m]) return not found </syntaxhighlight> We assume all the substrings have a fixed length ''m''. A naïve way to search for ''k'' patterns is to repeat a single-pattern search taking O(''n''+''m'') time, totaling in O((''n''+''m'')''k'') time. In contrast, the above algorithm can find all ''k'' patterns in O(''n''+''km'') expected time, assuming that a hash table check works in O(1) expected time.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)