![d75ac9fd434b474a27d43f9f5d632171.png](https://img-blog.csdnimg.cn/img_convert/d75ac9fd434b474a27d43f9f5d632171.png)
题目链接:https://leetcode-cn.com/problems/shortest-palindrome/
题目链接:
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例:
示例 1:
输入: "aacecaaa"
输出: "aaacecaaa"
示例 2:
输入: "abcd"
输出: "dcbabcd"
思路:
思路一:暴力^1
时间复杂度为:
思路二:递归^2
时间复杂度为:
思路三:KMP^3
强烈推荐如何更好的理解和掌握 KMP 算法? - 海纳的回答 - 知乎,多看几遍!
用kmp找从位置0
最长回文子串。
时间复杂度:
代码:
思路一:
class Solution:
def shortestPalindrome(self, s: str) -> str:
r = s[::-1]
for i in range(len(s) + 1):
if s.startswith(r[i:]):
return r[:i] + s
思路二:
class Solution:
def shortestPalindrome(self, s: str) -> str:
j = 0
# 找到从头开始,最长的回文子串
for i in range(len(s) - 1, -1, -1):
if s[i] == s[j]: j += 1
if j == len(s): return s
# 后缀
suffix = s[j:]
return suffix[::-1] + self.shortestPalindrome(s[0:j]) + suffix
思路三:
class Solution:
def shortestPalindrome(self, s: str) -> str:
def get_table(p):
table = [0] * len(p)
i = 1
j = 0
while i < len(p):
if p[i] == p[j]:
j += 1
table[i] = j
i += 1
else:
if j > 0:
j = table[j - 1]
else:
i += 1
j = 0
return table
table = get_table(s + "#" + s[::-1])
return s[table[-1]:][::-1] + s
更多题解:
九四干:[LeetCode] 题目汇总(持续更新)zhuanlan.zhihu.com![1f4846a3d3a020924a18b7fdd16058f9.png](https://img-blog.csdnimg.cn/img_convert/1f4846a3d3a020924a18b7fdd16058f9.png)
![0419f0cf3235918efb46270a9e1ecadf.png](https://img-blog.csdnimg.cn/img_convert/0419f0cf3235918efb46270a9e1ecadf.png)