题目链接:https://leetcode-cn.com/problems/shortest-palindrome/
题目链接:
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例:
示例 1:
输入: "aacecaaa"
输出: "aaacecaaa"
示例 2:
输入: "abcd"
输出: "dcbabcd"
思路:
思路一:暴力[1]
时间复杂度为:(O(n^2))
思路二:递归[2]
时间复杂度为:(O(n^2))
思路三:KMP[3]
强烈推荐如何更好的理解和掌握 KMP 算法? - 海纳的回答 - 知乎,多看几遍!用kmp找从位置0
最长回文子串。
时间复杂度:(O(n))
代码:
思路一:
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
https://leetcode.com/problems/shortest-palindrome/discuss/60099/AC-in-288-ms-simple-brute-force[ ↩︎
https://leetcode.com/problems/shortest-palindrome/discuss/60098/My-7-lines-recursive-Java-solution ↩︎
https://leetcode.com/problems/shortest-palindrome/discuss/60113/Clean-KMP-solution-with-super-detailed-explanation ↩︎