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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值