KMP算法伪码

KMP-MATCHER(T, P)

n <- length[T]
m <- length[P]
pi <- COMPUTE-PREFIX-FUNCTION(P)  // pi is just the pattern of P string
q <- 0
for i <- 1 to n 
    do while q > 0 and P[q+1] != T[i]
        do q <- pi[q]
    if P[q+1] = T[i]
        then q <- q+1
    if q = m
        then print "pattern occurs with shift" i-m
        q <- pi[q]

COMPUTE-PREFIX-FUNCTION(P)
m <- length[P]
pi[1] <- 0
k <- 0
for q <- 2 to m 
    do while  k > 0 and P[k+1] != P[q]
        do k <- pi[k]
    if P[k+1] = P[i]
        then k <- k+1
    pi[q] <- k
return pi




你可能感兴趣的:(算法)