[Leetcode]5. Longest Palindromic Substring

Problem:

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

Example:
Input: “babad”
Output: “bab”

Note: “aba” is also a valid answer.
Example:
Input: “cbbd”
Output: “bb”

思路:
1. 暴力枚举。双层循环遍历所有的substring(O(n^2)),然后用O(n)来对每一个substring进行判断是否回文(这里可以采用两头向中间靠近的方法,使得时间缩短一点点)。因为这一点修改,这暴力枚举法居然也Accepted。
2. 中心展开法。LeetCode上的solutions中,我觉得比较容易理解与实现的是中心展开发。主要思路就是对于待测字符串的每一个字符,以其为中心向左右展开,求能得到的最长回文子字符串。这个可以用递归来解决。

Solution 1 :

def isPalindrome(s):
    i = 0
    j = len(s)-1
    while i <= j:
        if s[i] != s[j]:
            return False
        i=i+1
        j=j-1
    return True


class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        size = len(s)
        i = 0
        j = 0
        if len(s) != 0:
            returnStr = s[0]
        while i < size:
            j = i
            while j < size:
                tmpstr = s[i:j+1]
                if isPalindrome(tmpstr) and len(tmpstr) > len(returnStr):
                    returnStr = tmpstr
                j = j + 1
            i=i+1

        return returnStr

Solution 2 :

def findneighbor(index1,index2,s,pureTag):
    if index1-1 < 0 :
        if index2+1 < len(s) and s[index2+1] == s[index2] and pureTag:
            return findneighbor(index1,index2+1,s,pureTag)
        else:
            return s[index1:index2+1]
    elif index2 + 1 >= len(s):
        return s[index1:index2+1]
    elif s[index1-1] == s[index2+1]:
        pureTag = True if s[index1-1] == s[index1] and pureTag else False
        return findneighbor(index1-1,index2+1,s,pureTag)
    elif s[index2+1] == s[index2] and pureTag:
        return findneighbor(index1,index2+1,s,pureTag)
    else:
        return s[index1:index2+1]

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        size = len(s)
        if size != 0:
            returnStr = s[0]
        i = 0
        while i < size:
            pureTag = True
            tmpStr = findneighbor(i,i,s,pureTag)
            if len(tmpStr) > len(returnStr):
                returnStr = tmpStr
                if len(tmpStr)+i == len(s):
                    break
            i=i+1
        return returnStr
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值