Python | Leetcode Python题解之第214题最短回文串
题目:
题解:
class Solution:
def shortestPalindrome(self, s: str) -> str:
n = len(s)
fail = [-1] * n
for i in range(1, n):
j = fail[i - 1]
while j != -1 and s[j + 1] != s[i]:
j = fail[j]
if s[j + 1] == s[i]:
fail[i] = j + 1
best = -1
for i in range(n - 1, -1, -1):
while best != -1 and s[best + 1] != s[i]:
best = fail[best]
if s[best + 1] == s[i]:
best += 1
add = ("" if best == n - 1 else s[best+1:])
return add[::-1] + s
原文地址:https://blog.csdn.net/Mopes__/article/details/140167932
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!