码迷,mamicode.com
首页 > 其他好文 > 详细

5. Longest Palindromic Substring

时间:2018-10-05 13:54:00      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:简单   while   思路   val   find   sub   mic   not   +=   

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

标签:简单   while   思路   val   find   sub   mic   not   +=   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!