5. Longest Palindromic Substring
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:1
2
3Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Idea
This is interval dp problem. Thus, we should build up a 2-d dp matrix to store information:
dp[i][j] represent whether s[i:j+1] is a palindromic substring or not.
Notice that ‘aa’ and ‘aca’ is palindromic string.
Code
1 | class Solution(object): |