首页 > 其他 > 详细

5. Longest Palindromic Substring

时间:2018-10-05 12:58:14      阅读:116      评论:0      收藏:0      [点我收藏+]

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"

Solution1:(不能AC,会MLE)

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)<=1:
            return s
        if len(s)==2:
            if s[0]==s[1]:
                return s
            else:
                return s[0]
        def judge(s):
            for i in range(int(len(s)/2)+1):
                if s[i]!= s[len(s)-1-i]:
                    return False
            return True
        length = len(s)
        for i in range(length,1,-1):
            for j in range(0,len(s)-length+1):
                if judge(s[j:j+length]):
                    return s[j:j+length]
            length -= 1
        if length == 1 :
            return s[0]

一个很简单的思路,从长向短找,判断是否是回文序列。找到最长的回文序列输出出来。

Solution2:


class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        def solve(s,i,j):
            while i>=0 and j<len(s) and s[i]==s[j]:
                i -= 1
                j += 1
            return s[i+1:j]
        res = ‘‘
        for i in range(len(s)):
            temp = solve(s,i,i)
            if len(temp) > len(res):
                res = temp
            temp = solve(s,i,i+1)
            if len(temp) > len(res):
                res = temp
        return res

从中间向两边扩展,分别从中心出发寻找以其为中心的最长序列。

5. Longest Palindromic Substring

原文:https://www.cnblogs.com/bernieloveslife/p/9742059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!