美文网首页
Leetcode5-Longest Palindromic Su

Leetcode5-Longest Palindromic Su

作者: 数据科学爱好者 | 来源:发表于2018-10-10 00:35 被阅读6次
    问题描述

    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"

    算法思路

    两种方法均可解决该问题,其中,第一种方法比较复杂,但是效率更高,第二种方法比较容易理解,但是效率较低。运行时间比较(88 ms < 3472 ms)。

    代码实现(Python3)

    方法一:

    class Solution:
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            if len(set(s)) == 1:
                return s
            elif s == s[::-1]: # s is already a palindrome
                return s
            
            Len   = 1
            start = 0
            for i in range(1, len(s)): # index values of string
                p1, p2 = i - Len, i + 1  
                if p1 >= 1:
                    temp = s[p1 - 1 : p2]
                    if temp == temp[::-1]:
                        start = p1 - 1
                        Len += 2
                        continue
                if p1 >= 0:
                    temp = s[p1:p2]
                    if temp == temp[::-1]:
                        start = p1
                        Len += 1
            return s[start:start + Len]
    

    方法二:

    class Solution:
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            if len(s) == 0: return ""
            self.longestP = s[0]
    
            def expand(s, l, r):
                while l >= 0 and r < len(s):
                    if s[l] == s[r]:
                        sub = s[l:r + 1]
                        if len(sub) > len(self.longestP):
                            self.longestP = sub
                        l = l - 1
                        r = r + 1
                    else:
                        break
    
            for i in range(len(s)):
                l, r = i, i + 1
                expand(s, l, r) # to find even substrings
                l, r = i - 1, i + 1
                expand(s, l, r) # to find odd substrings
    
            return self.longestP
    
    参考资料
    1. https://leetcode.com/problems/longest-palindromic-substring/ longest-palindromic-substring
    2. https://leetcode.com/problems/longest-palindromic-substring/discuss/172203/Python-Simple-Solution-O(n2)-time-and-O(1)-space Python - Simple Solution - O(n^2) time and O(1) space

    相关文章

      网友评论

          本文标题:Leetcode5-Longest Palindromic Su

          本文链接:https://www.haomeiwen.com/subject/ctuuaftx.html