[Leetcode]214. Shortest Palindrome@python

来源:互联网 发布:淘宝删除销量和评价 编辑:程序博客网 时间:2024/06/12 00:59

题目

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.

For example:

Given “aacecaaa”, return “aaacecaaa”.

Given “abcd”, return “dcbabcd”.

题目要求

给定一个字符串,允许在字符串的前面添加字符,得到通过这种方法可以生成的最短的回文字符串。

解题思路

此题借鉴了书影的解题方法,并且参考了阮一峰对于KMP字符串匹配算法的解释。
最Naive的生成回文的方法是直接将给定字符串翻转后的字符串添加在字符串前面。但是这样生成的字符串并不是最短的回文,因为反转字符串的后缀可能和给定字符串的前缀有公共的部分,这部分是可以去掉一部分的,如以下情况
.
代码中用到了KMP算法用的部分匹配数组。
给定字符串s,其反转字符串为rev_s,s + “#” + rev_s的部分匹配数组的最后一位共有元素长度就是反转字符串rev_s后缀和s前缀相同的部分的长度。之所以用”#”,是为了在计算部分匹配数组时,可以将rev_s和s进行分离,使得他们连起来的字符串的前缀和后缀不会跨越这两个子字符串。

代码

class Solution(object):    def shortestPalindrome(self, s):        """        :type s: str        :rtype: str        """        rev_s = s[::-1]        l = s + "#" +  rev_s        p = [0] * len(l)        for i in range(1,len(l)):            j = p[i - 1]            while j > 0 and l[i] != l[j]:                j = p[j - 1]            p[i] = j + (l[i] == l[j])        return rev_s[:len(s) - p[-1]] + s
0 0