-1

The code works, however, it is not efficient when inputs are very large. How can I optimize this?

Longest Palindromic Substring: Given a string s, return the longest palindromic substring in s.

def longestPalindrome(self, s: str) -> str:
    ans = ""
    perm = ""
    for i in s:
        perm = ""
        for j in s:
            perm += j
            if perm == perm[::-1] and len(perm) > len(ans):
                ans = perm
        s = s[1:]
        
    return ans
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Does this answer your question? [Write a function that returns the longest palindrome in a given string](https://stackoverflow.com/questions/1115001/write-a-function-that-returns-the-longest-palindrome-in-a-given-string) – j1-lee Jul 06 '21 at 23:29
  • See also [How to check for palindrome using Python logic](https://stackoverflow.com/q/17331290/12345551) – He3lixxx Jul 07 '21 at 22:40

1 Answers1

0
def palindrome(word):
    return word[::-1] == word:
  • The anecdote is cute, but please just link to the existing answer; don't make it a separate post here. Also, the `if` is redundant. Simply return the value of the Boolean expression. `return word[::-1] == word` does the job in one statement. – Prune Jul 06 '21 at 23:45
  • Understood! Thanks –  Jul 07 '21 at 19:43