Problem
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
If input string has length less than 2, simply return the string.
-
To find palindromic string, we can loop through the input string character and each character we make it as the middle of the palindromic.
-
Palindrom has 2 situations: First situation,
abcba
, here,c
is the middle; Second situation,abba
, here,bb
is the middle. -
In each iteration, we make the current character as the middle. We need to check if the current character is the same as its next character, if not the same, then we consider first situation; else, we consider the second situation.
-
We can define
left
andright
pointing the middle characters. In the fist situation,left
andright
arec
. In the second situation,left
is firstb
,right
is secondb
. -
Then, we compare the middle’s left character and middle’s right character, in other words,
str[left-1]
comparing tostr[right+1]
. While they are the same,left = left-1
andright=right+1
. After the while loop,left
is pointing at the palindrome’s beginning index, andright
is pointing at the palindrome’s last index.right-left+1
is its length. At the end of each iteration, we update the maximum length. -
After we finish the loop using the last index of the string as middle, we can return the longest pralindrome substring using the
left
and its maximum length.
Solution 1
(Time: $O(n^2)$; Space: $O(1)$)
1 |
|
Solution 2
(Dynamic Programming Time: $O(n^2)$; Space: $O(n^2)$)
1 |
|