[LC] 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"

Time: O(N^2)
class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s) <= 1:
            return s
        self.res = ''
        for i, char in enumerate(s):
            self.helper(i, i, s) # odd
            self.helper(i, i + 1, s) # even
        return self.res
    
    def helper(self, start, end, s, even=False):  
        while start >= 0 and end < len(s):
            if s[start] == s[end]:
                if end - start >= len(self.res):
                    self.res = s[start: end + 1]
                start -= 1
                end += 1
            else:
                return
        
        

 

你可能感兴趣的:([LC] 5. Longest Palindromic Substring)