[Leetcode]5. Longest Palindromic Substring

来源:互联网 发布:淘宝注册还要拨打号码 编辑:程序博客网 时间:2024/05/29 02:49

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 Trueclass 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
0 0
原创粉丝点击