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,cis the middle; Second situation,abba, here,bbis 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
leftandrightpointing the middle characters. In the fist situation,leftandrightarec. In the second situation,leftis firstb,rightis 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-1andright=right+1. After the while loop,leftis pointing at the palindrome’s beginning index, andrightis pointing at the palindrome’s last index.right-left+1is 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
leftand 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 | |