Z函式

gebeng發表於2024-03-31

image

s = input()
n = len(s)
z = [0] * n
left,right = 0,0
# z[i]表示s和s[i:]的LCP長度,規定z[0] = 0!
for i in range(1,n):
    # 如果在z-box裡,那麼更新它的z[i]的值!
    if i <= right:
        z[i] = min(z[i - left],right - i + 1)
    # 相當於暴力更新
    while i + z[i] < n and s[z[i]] == s[i + z[i]]:
        # 更新 z-box!
        left,right = i,i + z[i]
        z[i] += 1

print(z)

相關文章