Main Page | See live article | Alphabetical index

String searching algorithm

String searching algorithms are an important class of string algorithms that try to find a place where one or several strings (also called patterns) are found within a larger string or text.

Let Σ be an alphabet (finite set). Formally, both the pattern and searched text are concatenation of elemements of Σ. The Σ may be usual human alphabet (A-Z). Other applications may use binary alphabet (Σ = {0,1}) or DNA alphabet (Σ = {A,C,G,T}) in bioinformatics.

Table of contents
1 Basic classification
2 Other classification

Basic classification

The various algorithms can be classified by the number of patterns each uses.

Single pattern algorithms

Algorithms
Preprocessing Time Matching Time
Naïve string search algorithm 0 (no preprocessing) O((n-m+1)m)
Rabin-Karp algorithm θ(m) O((n-m+1)m)
Finite Automata O(m|Σ|) θ(n)
Knuth-Morris-Pratt algorithm θ(m) θ(n)
Boyer-Moore string search algorithm
Baeza-Yates and Gonnet string search algorithm
Where m and n are the length of the two strings being compared.

Algorithms using finite set of patterns

Algorithms using infinite number of patterns

Naturally, the patterns can not be enumerated in this case. They are represented usually by a regular grammar or regular expression.

Other classification

Other classification approaches are possible. One of the most common uses preprocessing as main criteria.

Classes of string searching algorithms
Text not preprocessed Text preprocessed
Patterns not preprocessed Elementary algorithms Index methods
Patterns preprocessed Constructed search engines Signature methods

Naïve string search

The simplest and least efficient way to see where one string occurs inside another is to check each place it could be, one by one, to see if it's there. So first we see if there's a copy of the needle in the first few characters of the haystack; if not, we look to see if there's a copy of the needle starting at the second character of the haystack; if not, we look starting at the third character, and so forth. In the normal case, we only have to look at one or two characters for each wrong position to see that it's a wrong position, so in the average case, this takes O(n + m) steps, where n is the length of the haystack and m is the length of the needle; but in the worst case, searching for a string like "aaaab" in a string like "aaaaaaaaab", it takes O(nm) steps.

stubs

KMP computes a deterministic finite state automaton that recognizes inputs with the string to search for as a suffix, so it doesn't need to back up. Boyer-Moore starts searching from the end of the needle, so it can usually jump ahead a whole needle-length at each step. Baeza-Yates and Gonnet uses bits in a word to keep track of whether the previous N characters were a prefix of the search string, and is therefore adaptable to fuzzy string searching etc.

External Links

Huge (maintained) list of pattern matching links