Leetcode: Longest Palindromic Substring

Question

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Hide Tags String
Hide Similar Problems (H) Shortest Palindrome (E) Palindrome Permutation

Solution 1

time complexity: O(n^2)
space complexity: O(1)

Get ideaf from here, here2,here3

class Solution(object):
    def longestPalindrome(self, s):
        """ :type s: str :rtype: str """

        if len(s)==0:
            return None
        if len(s)==1:
            return s

        res = ''
        for i in range(len(s)):
            temp = self.helper(s, i, i)
            if len(temp)>len(res):
                res = temp

            temp = self.helper(s, i, i+1)
            if len(temp)>len(res):
                res = temp

        return res

    def helper(self, s, start, end):
        while start>=0 and end<len(s) and s[start]==s[end]:
            start -= 1
            end += 1

        return s[start+1:end]

Solution 2

dynamic programming
Get idea from here

你可能感兴趣的:(Leetcode: Longest Palindromic Substring)