KMP prefix table

前端 未结 7 1031
说谎
说谎 2020-12-02 07:58

I am reading about KMP for string matching.
It needs a preprocessing of the pattern by building a prefix table.
For example for the string ababaca

相关标签:
7条回答
  • 2020-12-02 08:37

    I have tried my hands using the Javascript, Open for suggestions.

    const prefixArray = function (p) {
    let aux = Array(p.length).fill(0);
    
    // For index 0 the matched index will always be 0, so we will we start from 1
    let i = 1;
    let m = 0; // mismatched index will be from 0th
    
    // run the loop on pattern length
    while ( i < p.length) {
    
        // 3 Cases here
        // First when we have a match of prefix and suffix of pattern
        if(p.charAt(i) === p.charAt(m)) {
            // increment m
            m++;
            // update aux index
            aux[i] = m;
            // update the index.
            i++;
        } 
        // Now if there is no match and m !=0 means some match happened previously
        // then we need to move back M to that index
        else if(p.charAt(i) !== p.charAt(m) && m !== 0) {
            m = aux[m-1];
            // we dont want to increment I as we want to start comparing this suffix with previous matched
        } else {
            // if none of the above conditions then
            // just update the current index in aux array to 0
            aux[i] = 0; // no match
            i++; // shift to the next char
        }
    }
    
    return aux; 
    }
    
    0 讨论(0)
提交回复
热议问题