Search code examples
pythonsubstringpalindrome

Leetcode 5 Longest Palindromic Substring (python)


Why do I get wrong answer using this code? I try to find all possible substrings and find the longest one after storing them into a list. Thank you for your help!

class Solution:
    def longestPalindrome(self, s: str) -> str:
        
            length  = len(s)
            #get all possible substrings
            combinations = [s[i:j] for i in range(length) for j in range(i+1, length+1)]

            #print(combinations)

            rev = s[::-1]
            rev_combinations = [rev[i:j] for i in range(length) for j in range(i+1, length+1)]

            #print(rev_combinations)

            pan_l = []
            for i, c in enumerate(combinations)):
                if combinations[i] == rev_combinations[i]:
                    pan_l.append(combinations[i])
            
            if pan_l:
                y = max(pan_l, key=len)
                return y
            else:
                return s[0]
    
            
        
        
        

Solution

  • Consider the string "ab". This will give combinations == ['a', 'ab', 'b']. Its reverse, "ba", gives rev_combinations == ['b', 'ba', 'a']. You see that none of the items match at their exact positions, even though 'a' and 'b' are both trivial palindromes.

    A better way to deal with this would be to check each substring if it is a palindrome:

    pan_l = []
    for substring in combinations:
        if substring == substring[::-1]: # this substring is a palindrome
            pan_l.append(substring)
    

    You then don't need rev or rev_combinations at all.