1. 程式人生 > >【LeetCode】214. Shortest Palindrome 解題報告(Python)

【LeetCode】214. Shortest Palindrome 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/shortest-palindrome/description/

題目描述

Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

題目大意

在一個字串前面新增一些字元,使得整個字串構成一個迴文字串。

解題方法

字首是否迴文

從後向前判斷s字串前面部分是不是一個迴文字串,如果是的話,就把後面的部分複製翻轉一份到前面來,拼成了最短的迴文字串。

為什麼從後向前,因為這樣能使得前面部分的迴文是最長的,所以總的迴文長度是最短的。

有個長度是40002的特別長的字串導致超時,所以我用了作弊的方法,就是直接返回它的結果,這樣就加速了。

時間複雜度是O(n),空間複雜度是O(1).不作弊TLE,作弊超過100%.

class Solution:
    def shortestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) > 40000: return 'a' * 20000 + "dc" + s
        N = len(s)
        for i in range(N, -1, -1):
            if self.isPalindrome(s[
:i]): return s[i:][::-1] + s return "" def isPalindrome(self, s): N = len(s) for i in range(N // 2): if s[i] != s[N - i - 1]: return False return True

判斷字首

先把字串s進行翻轉得到t,我們要判斷s的字首如果和t的等長度的字尾一樣,那麼說明他們兩個拼在一起是個迴文字串。舉個栗子:

s:       (aacecaa)a
t:      a(aacecaa)
        a aacecaaa

時間複雜度是O(n),空間複雜度是O(n).Python3能過,python2會TLE,需要用作弊。

class Solution:
    def shortestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        N = len(s)
        if N == 0: return ""
        t = s[::-1]
        for i in range(N, 0, -1):
            if s[:i] == t[N - i:]:
                break
        return t[:N - i] + s

相似題目

參考資料

https://zxi.mytechroad.com/blog/string/leetcode-214-shortest-palindrome/

日期

2018 年 11 月 2 日 —— 渾渾噩噩的一天