|
发表于 2023-9-2 15:48:29
|
显示全部楼层
在你提供的代码中,有一个问题导致了next数组求解不正确。问题出现在while循环内部的判断条件上。
请将以下代码段:
- while (t[ i] != t[j]) and (j > 0):
- j = next[j - 1]
复制代码
修改为:
- while (j > 0) and (t[ i] != t[j]):
- j = next[j - 1]
复制代码
这样修改后,再运行代码求解KMP算法的next数组应该能够得到正确的结果。
修改后的完整代码如下所示:
- def getnext(t):
- n = len(t)
- next = [0 for i in range(n)]
- j = 0 # i:前缀尾,j:后缀尾
- for i in range(1, n):
- while (j > 0) and (t[ i] != t[j]):
- j = next[j - 1]
- if t[ i] == t[j]:
- j += 1
- next[ i] = j
- return next
- t = input("输入子串:")
- res = getnext(t)
- print(res)
复制代码
希望这次修改能够解决你的问题。如果还有其他疑问,请随时提问。
如果问题已经解决,请设置最佳答案 |
|