KMP prefix table

前端 未结 7 1048
说谎
说谎 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:35

    Python Implementation

    p='ababaca'
    
    l1 = len(p)
    
    j = 0
    i = 1
    prefix = [0]
    
    while len(prefix) < l1:
        if p[j] == p[i]:
            prefix.append(j+1)
            i += 1
            j += 1
        else:
            if j == 0:
                prefix.append(0)
                i += 1
            if j != 0:
                j = prefix[j-1]
    
    print prefix
    

提交回复
热议问题