z-algorithm: slightly faster by allocating and using an array.