Relation between KMP algorithm and Z algorithm

后端 未结 3 2025
星月不相逢
星月不相逢 2021-02-03 13:43

KMP and Z algorithms are well known algorithms for string searching,

KMP algorithm deals with finding the patterns through a KMP f

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-03 14:31

    I think this will do it.

    def Z(lps):
        # First assume that we always need to restart when we find a mismatch.
        Z = [0] * len(lps)
    
        # Step through adjacent pairs.
        itr = enumerate(zip(lps, lps[1:]), start=1)
        for i, (prev, cur) in itr:
            if cur <= prev: # suffix stopped growing
                Z[i - prev] = prev # Mark this suffix at its beginning.
    
        # Ending the string is also a way to stop growing the suffix.
        if cur > 0: # if we were still growing a suffix
            # At end of loop, cur is the new prev, and i+1 is the new i.
            # (i == len(lps) - 1, cur == lps[-1])
            Z[i+1 - cur] = cur
    
        return Z
    

    Samples:

    Z([0,0,0,1,2]) #=> [0,0,0,2,0]
    Z([0,0,1,2,1,2]) #=> [0,0,2,0,2,0]
    

提交回复
热议问题