LeetCode 5.Longest Palindromic Substring (Python)兼翻译

来源:互联网 发布:海洋cms视频 编辑:程序博客网 时间:2024/05/21 08:46

5. Longest Palindromic Substring

最长回问子串

本题来自LeetCode OJ


题目翻译

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

给定一个字符串s,找出s中的最长回文子串。你可以假定s的最大长度为1000。
例1:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

例2:

Input: "cbbd"Output: "bb"

题目分析

回文的特点就是正着和反着是相同的,或者说是镜面的。所以用sr表示倒叙后的s字符串,如果他是回文子串的一个充要条件就是它存在sr中且本身为回文。

代码示例

class Solution(object):    def longestPalindrome(self, s):        """        :type s: str        :type sr: str        :rtype: str        """        sr = "".join(reversed(s)) # sr为s的倒序        answerLen = 1 # 最短的回文子串即为一个字符        try:            answer = s[0] # 取第一个字符作为默认回文        except:            return None        i = 0        # 因为最后一个字符肯定不需要去判断        while i < len(s) - 1:            plus = 2            # plus-1为回文的字符串的现有长度,致所有加plus<=len(s)的判断条件是由于避免出现s本身为回文            while sr.find(s[i:i+plus]) != -1 and plus <= len(s)-i:                plus = plus + 1            if plus-1 > answerLen:                taskAnswer = s[i:i+plus-1]                # 这时候需要判断备选的答案本身是否为回文                if taskAnswer == taskAnswer[::-1]:                    answer = taskAnswer                    answerLen = len(answer)            i = i + 1        return answer

0 0