zoukankan      html  css  js  c++  java
  • 5. 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"

    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
    

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

  • 相关阅读:
    ARTS 计划第四周
    ARTS 计划第三周周
    计划表的科学设定
    C/C++内存分配
    ARTS 计划第二周周
    jsoncpp 和 libcurl的编译与使用 vs2010
    ARTS 计划第一周
    unix中的v节点和i节点
    百度地图demo
    带有定位当前位置的百度地图web api 前端代码
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9742059.html
Copyright © 2011-2022 走看看