[LintCode 200] 最长回文字符串(Python)

来源:互联网 发布:第二磨牙长歪了 知乎 编辑:程序博客网 时间:2024/06/07 22:36

题目描述

给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。

样例
给出字符串 “abcdzdcab”,它的最长回文子串为 “cdzdc”。

思路

遍历字符串,假设把当前遍历到的元素当做回文中间数。当最长回文长度是偶数的,那么中间数应该和下个数相等,然后其余的数都对称相等;当最长回文长度是奇数的,那么其余的数应都对称相等。

代码

class Solution:    """    @param: s: input string    @return: the longest palindromic substring    """    def longestPalindrome(self, s):        # write your code here        res = ''        if s is None or len(s) == 0:            return res        for i in range(len(s)):            j = i - 1            k = i + 1            tmp = s[i]            while k < len(s) and s[k] == s[i]:                tmp = tmp + s[k]                k += 1            while j >= 0 and k < len(s) and s[j] == s[k]:                tmp = s[j] + tmp + s[k]                j -= 1                k += 1            if len(tmp) > len(res):                res = tmp        return res

复杂度分析

时间复杂度O(n),空间复杂度O(1)

原创粉丝点击