KMP Substring Search With Failure Table

The failure table records the longest equal prefix-suffix per position, letting the scan reuse matched characters instead of restarting.

RustData Integrity

Code

rustsnippet
45 lines
// failure table: length of the longest proper prefix that is also a suffix at pattern[i]
fn failure_table(pattern: &[u8]) -> Vec<usize> {
    let mut table = vec![0; pattern.len()];
    let mut prefix = 0;
    for i in 1..pattern.len() {
        while prefix > 0 && pattern[i] != pattern[prefix] {
            prefix = table[prefix - 1];
        }
        if pattern[i] == pattern[prefix] {
            prefix += 1;
        }
        table[i] = prefix;
    }
    table
}

fn find(text: &str, pattern: &str) -> Option<usize> {
    if pattern.is_empty() {
        return Some(0);
    }
    let (text, pattern) = (text.as_bytes(), pattern.as_bytes());
    let table = failure_table(pattern);
    let mut matched = 0;
    for (i, &byte) in text.iter().enumerate() {
        while matched > 0 && byte != pattern[matched] {
            matched = table[matched - 1];
        }
        if byte == pattern[matched] {
            matched += 1;
            if matched == pattern.len() {
                return Some(i + 1 - matched);
            }
        }
    }
    None
}

fn main() {
    println!("failure table: {:?}", failure_table(b"ababaca"));
    println!(
        "find: {:?}",
        find("bamboo ababaca", "ababaca")
    );
    println!("find missing: {:?}", find("bamboo", "zzz"));
}

How it works

KMP Substring Search With Failure Table is built around the functions failure_table, find and main.

A single loop drives the file — for i in 1..pattern.len().

Points of care

  • The language toolchain itself is the only prerequisite.

Putting it to use

The one signature that matters here is fn failure_table(pattern: &[u8]) -> Vec<usize>

Output lines are prefixed (failure table:, find:, find missing:), making the effect of each step easy to see.

Launch the file; main takes over and steps through failure_table and find.

The core lines of the flow

return Some(i + 1 - matched);
return Some(0);
matched += 1;

Interactive Tools for This Topic

FAQ

What does KMP Substring Search With Failure Table print when run?
Execute the whole file; each printed line is prefixed with a label like `failure table:`, `find:`, `find missing:`.