leetcode5 Longest Palindromic Substring

leetcode第5道题,

题目如下:

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

题目解释:给定一个字符串S,找出最长的回文子串


这里提供两种解法:

1.最原始的做法,一个一个挑出子字符串判定是否为回文字符串能实现,但超时了

class Solution(object):
    #思路:逐一比较子串,找出最长回文子串
    
    #判断是否是回文字符
    def isPalind(self,ss,start,end):
        while start < end:
            if ss[start] != ss[end]:
                return False
            start += 1
            end -= 1
        return True
        
    def longestPalindrome(self, s):     #这个不就是先固定i,在依次移动右边位置,依次比较的嘛
        len_s = len(s)
        max_s,left,right = 0, 0, 0
        for i in range(len_s):
            j = i + 1
            while j < len_s:
                if self.isPalind(s, i, j):
                    if (j -i + 1) > max_s:
                        left,right = i, j
                        max_s = j - i + 1
                j += 1
        
        return s[left : right + 1]

2. 双指针两边扩展法

class Solution(object):     
    def longestPalindrome(self, s):  
        
#思路:双指针两边扩展,一往左,一往右,找相等
        # maxr,maxl,maxs = 0,0,0
        m1,m2,maxs = 0,0,0
        n = len(s)
        
        for i in range(n):
            #当回文字符串长度为偶数时,中间的相邻等,然后分别往左右扩展
            maxl = i
            maxr = i + 1
            while maxl >= 0 and maxr < n:
                if s[maxl] == s[maxr]:
                    if (maxr - maxl + 1) > maxs:
                        m1 ,m2 = maxl, maxr
                        maxs = maxr - maxl + 1
                    maxl -= 1
                    maxr += 1
                else:
                    break
                    
            #当回文字符串长度为奇数时,中间三数间隔为1等,再分别左右扩展
            maxl = i - 1
            maxr = i + 1
            while maxl >=0 and maxr < n:
                if s[maxl] == s[maxr]:
                    if (maxr - maxl + 1) > maxs:
                        m1 ,m2 = maxl, maxr
                        maxs = maxr - maxl + 1
                    maxl -= 1
                    maxr += 1
                else:
                    break
                    
        return s[m1 : m2 + 1]



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值