Longest Palindromic Substring

Posted LilyLiya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。

refer to: https://www.algoexpert.io/questions/Longest%20Palindromic%20Substring

Problem Statement

Analysis

穷举法

Code

def longestPalindromicSubstring(string):
    longest = ""
    for i in range(len(string)):
        for j in range(i, len(string)):
            substring = string[i:j+1]
            if len(substring) > len(longest) and isPalindrome(substring):
                longest = substring
    return longest

def isPalindrome(string):
    leftIdx = 0
    rightIdx = len(string) - 1
    while leftIdx < rightIdx:
        if string[leftIdx] != string[rightIdx]:
            return False
        leftIdx += 1
        rightIdx -= 1
    return True

Time complexity

O(n^ 3)-> embed for loops, O(n) for the isPalindrome function

extension to left and right direction method

Code

def longestPalindromicSubstring(string):
    currentLongest = [0,1]
    for i in range(1, len(string)):# traverse every index, and apply getLongestPalindromeFrom function
        odd = getLongestPalindromeFrom(string, i - 1, i + 1)
        even = getLongestPalindromeFrom(string, i - 1, i)
        longest = max(odd, even, key = lambda x: x[1] - x[0]) # use lambda to track the length of palindrome substrings
        currentLongest = max(longest, currentLongest, key = lambda x: x[1] - x[0])
    return string[currentLongest[0] : currentLongest[1]]
        
    
def getLongestPalindromeFrom(string, leftIdx, rightIdx): #check from center to both left and right direction
    while leftIdx >= 0 and rightIdx < len(string):
        if string[leftIdx] != string[rightIdx]:
            break
        leftIdx -= 1
        rightIdx += 1
    return [leftIdx + 1, rightIdx]

Time complexity

以上是关于Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

Longest Palindromic Substring

5. Longest Palindromic Substring

[Leetcode]Longest Palindromic Substring

LeetCode:Longest Palindromic Substring

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring