Leetcode Longest Palindromic Substring

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

 

Example 1:

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

Example 2:

Input: "cbbd"
Output: "bb"

 

被这个题卡了好久,还是编程太弱...主要是我觉得有的时候还是想太复杂了,忽略了程序的机械性><

主要思路:

就是solution里给出的最后的那种expand的方法

我总结的是expand的最小单位可以是针对个数为偶数的回文的两个字母,比如说"abba"中的"bb",和针对个数为奇数的回文的三个字母,比如说"dabad"中的"aba"。

还有一个专门用循环找回文的helper function

在循环的时候每次i增加1,因为不增加1,增加比如说回文后半段的长度,可能会跳过正确答案,导致部分测试无法通过

代码如下:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        length = len(s)
        #if length equals 0 or 1, return s
        if length == 0 or length == 1:
            return s
        else:
            i = 0
            max_len = 0
            sub = ''

           #两个字母为最小单位
            while i < length:
                if (i + 1) < length and s[i] == s[i + 1]:
                    max_len, sub = self.find_palindrome(s, i, i + 1, max_len, sub, length)
                i += 1
            i = 0

           #三个字母为最小单位
            while i < length:
                if (i + 1) < length and (i - 1) >= 0 and s[i - 1] == s[i + 1]:
                    max_len, sub = self.find_palindrome(s, i - 1, i + 1, max_len, sub, length)
                i += 1
            if max_len == 0:
                sub = s[0]
            return sub

    #循环来不断找回文的helper function
    def find_palindrome(self, s, i, j, max_len, sub, length):
        while i >= 0 and j < length and s[i] == s[j]:
            i -= 1
            j += 1
        i += 1
        if j- i > max_len:
            max_len = j - i
            sub = s[i: j]
        return max_len, sub

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值