# String Match

#### String Match Algorithm

The topic here is not a regular expression but string search algorithm. For example, find the position(s) of matched patterns in a loooong text.

The easiest implementation is:

1. check each character of the given pattern one by one
2. shift starting index by one
3. repeat 1 and 2

A performance of this brute-force search is O(n^2), which considered bad. When the given text is huge, it’s apparent.

#### How to effectively find matched pattern

There’s a few algorithms to effectively find the pattern. Among them, Knuth-Morris-Pratt (KMP) algorithm would be well-known algorithm. KMP uses prefix function to skip or find a pattern effectively. The performance of KMP is O(N+M) where N, M are the lengths of text and pattern respectively.

KMP is quite effective, however, understanding its idea is quite tough. Especially, a prefix function, which is also called failure function or partial match table, is a challenging part. Actually, it is an array, neither of function nor table.

This famous algorithm is explained in books and websites, so we can easily find many. Unfortunately, most of them don’t help to understand the idea so much except:

The Knuth-Morris-Pratt Algorithm in my own word

This blog post is really good. The key idea of prefix function is to find “the longest proper prefix of a substring which is also a suffix.” The blog post tells us what is it clearly using good examples.

Also, the idea how to find the pattern using prefix function is described with easy-to-understand illustrations.

#### Prefix function (a.k.a. failure function, matching table)

The prefix function (an array) will be created only from a pattern. We don’t use a text at all to compute values in prefix function. The function is used to see how the pattern matches itself. Based on this information, we can safely skip useless comparisons.

Here’s the code to calculate prefix function:

When the pattern is “ababaca”, above computes:

i 0 1 2 3 4 5 6
pattern[i] a b a b a c a
p[i] 0 0 1 2 3 0 1

#### Pattern search in text by prefix function

Once prefix function is computed, it’s time to search the pattern. This part absolutely use the given text. The rule is:

• find the length of characters matched
• if the matched length is the same as pattern, the pattern found
• look up the value in prefix function at index (matched length - 1)
• skip characters in the value at index (matched length -1)
• repeat

Below is the code to search the pattern:

#### Run the code and find the pattern

All parts are ready. It’s time to run the code and see the result.

Above prints,