Predict the output
What does this print?
pat = "abab"
border = [0] * len(pat)
k = 0
for i in range(1, len(pat)):
while k and pat[i] != pat[k]:
k = border[k - 1]
if pat[i] == pat[k]:
k += 1
border[i] = k
print(border)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [0, 0, 1, 2]
Right: 'aba' ends with 'a' and 'abab' ends with 'ab'.
After a mismatch, the border says how much of the pattern is already matched, so the search never steps back in the text.
Why not the others?
- B [0, 1, 2, 3]. A border must be shorter than the prefix itself.
- C [0, 0, 1, 1]. 'abab' starts and ends with 'ab', a border of length 2.