トピックへのリンク:https://leetcode-cn.com/problems/shortest-palindrome/
トピックリンク:
文字列を考えるとSは、パリンドローム配列に変換する前に文字列を追加することができます。検索とこのように最短で回文配列を変換することができる戻ります。
例:
例1:
输入: "aacecaaa"
输出: "aaacecaaa"
例2:
输入: "abcd"
输出: "dcbabcd"
アイデア:
思考:暴力1
時間の複雑さは、次のとおりです。\(O(^ N-2)\)
アイデアII:再帰2
時間の複雑さは、次のとおりです。\(O(^ N-2)\)
三つのアイデア:KMP 3
強くお勧めしますよりよく理解し、KMPアルゴリズムを習得する方法- ?ハイナーの答え-知っているほとんど、Duokanjibian!位置から見た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
2考えます:
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
3思考:
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 ↩