最长回文子串python暴力_LeetCode5最长回文子串-Python

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

示例 1:

输入: "babad"

输出: "bab"

注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"

输出: "bb"

class Solution:

def longestPalindrome(self, s):

"""

:type s: str

:rtype: str

"""

#最长回文串必然在最长公共子串中,从第一个字符开始,判断其是否为会问字符串

length = len(s)

result = ""

if length == 0 or length == 1:

return s

for i in range(length):

string = self.issub(s, i, length)

if len(string) > len(result):

result = string

return result

def issub(self, s, i, length):

j = 0

string1 = ""

string2 = ""

while(i - j >= 0 and i + j < length): ##回文串为奇数个

if s[i - j] != s[i + j]:

break

else:

j += 1

if j != 0:

string1 = s[i - j + 1 : i + j]

else:

string1 = s[i]

k = 0

while(i - k >= 0 and i + k + 1< length): ##回文串为偶数个

if s[i - k] != s[i + k + 1]:

break

else:

k += 1

if k != 0:

string2 = s[i - k + 1 : i + k + 1]

if len(string1) > len(string2):

string = string1

else:

string = string2

return string

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值