Longest palindromic substring#

Levels: level-4
Data structures: string
Algorithms: dynamic-programming

LeetCode

Description#

  • Given a string s, find the longest palindromic substring in s.
  • You may assume that the maximum length of s is 1000.

Example#

1Input: "babad"
2Output: "bab"
3Note: "aba" is also a valid answer.
1Input: "cbbd"
2Output: "bb"

Python Solution#

 1class Solution(object):
 2    def longestPalindrome(self, s):
 3        """
 4        :type s: str
 5        :rtype: str
 6        """
 7
 8        res = ""
 9        for i in range(len(s)):
10            # odd case, like "aba"
11            tmp = self.helper(s, i, i)
12            if len(tmp) > len(res):
13                res = tmp
14            # even case, like "abba"
15            tmp = self.helper(s, i, i + 1)
16            if len(tmp) > len(res):
17                res = tmp
18        return res
19
20    # get the longest palindrome, l, r are the middle indexes
21    # from inner to outer
22    def helper(self, s, l, r):
23        while l >= 0 and r < len(s) and s[l] == s[r]:
24            l -= 1
25            r += 1
26        return s[l + 1:r]