Naive string matching
Put the pattern under every possible position of the text and compare character by character; simple, but O((n − m + 1)·m) in the worst case.
We want every place where the pattern P (of length m) occurs in the text T (of length n). The simplest
method: put the pattern under every shift s = 0 … n − m and compare left to right until the characters differ.
- Time:
O((n − m + 1)·m) - Space:
O(1) - CLRS, section 32.1
- Horowitz–Sahni, chapter 2
The pattern abaa occurs once in the text acaabcabaabac, at shift 6; every shift is tried on its own.
def naive_match(T, P):n, m = len(T), len(P)matches = []for s in range(n - m + 1):q = 0while q < m and T[s + q] == P[q]:q = q + 1if q == m:matches.append(s)return matches
Start
Local variables
Orange = changed in this step
Call stack
- naive_match()line 1
Explanation
The idea
We want every place where the pattern P (of length m) occurs in the text T (of length n). The simplest
method: put the pattern under every shift s = 0 … n − m and compare left to right until the characters differ.
Cost
In the worst case (like aaa…ab) almost m comparisons are needed at every shift: O((n − m + 1)·m). The trouble is
that what earlier comparisons learned is thrown away; KMP keeps it and reaches O(n + m).
What to watch in the trace
- The pattern is drawn under the text at shift
s; its filled cells have matched the text so far.