Найти - Пользователи
Полная версия: Z-функция
Начало » Python для экспертов » Z-функция
1
Andrew22528
Всем привет. Не могли ли вы найти ошибку в коде для нахождения Z-функции строки(Python3).
s = list(input())
n = len(s)
z = [0] * n 
z[0] = n
l = r = 0
i = 1
while i < n:
    if i > r:
        j = 0
        while (j + i < n) and (s[i + j] == s[j]):
            z[i] = j
            j += 1
            l = i
            r = i + j - 1
    else:
        if z[i - l] < r - i + 1:
            z[i] = z[i - l]
        else:
            j = 1
            while j + r < n and s[r + j] == s[r - i + j]:
                z[i] = r - i + j
                l = i
                r = r + j - 1
                j += 1
    i += 1
print(z)
py.user.next
>>> def zfun(s):
...     out = []
...     if not s: return out
...     i, slen = 1, len(s)
...     out.append(slen)
...     while i < slen:
...         left, right = 0, i
...         while right < slen and s[left] == s[right]:
...             left += 1
...             right += 1
...         out.append(left)
...         i += 1
...     return out
... 
>>> zfun('abcdabscabcdabia')
[16, 0, 0, 0, 2, 0, 0, 0, 6, 0, 0, 0, 2, 0, 0, 1]
>>> zfun('')
[]
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB