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:
|
|
Example 2:
|
|
Dynamic Programming Solution
Let dp[i][j]
indicates that s[i:j+1]
is a palindromic sequence, we have
$$ dp[i][j] = \begin{cases} True, & \text{$i$ = $j$} \\ s[i] = s[j], & \text{$j$ - $i$ = 1} \\ (s[i] = s[j]) \ \text{and} \ dp[i+1][j-1], & \text{$j$ - $i$ > 1} \end{cases} $$
|
|
Filling order is as described below:
i\j | b | a | b | a | d |
---|---|---|---|---|---|
b | 0 | 1 | 3 | 6 | 10 |
a | 2 | 4 | 7 | 11 | |
b | 5 | 8 | 12 | ||
a | 9 | 13 | |||
d | 14 |
|
|
Palindrome Ad-hoc Solution
Set $i$ to be the center of palindrome sunstring, $j$ to be the radius, we can expand from center to side to valid the substring:
- Odd length substring:
- Expand from $(i, i)$, in which $j=0$, $L=i-j, R=i+j$, length of the substring is $2j+1$, $r_{max} = i$
- Even length substring:
- Expand from $(i-1, i)$, in which $j=0$, $L=i-1-j, R=i+j$, length of the substring is $2j+2$, $r_{max} = i$
i-j | i-1 | i | i+1 | i+r | |||||
---|---|---|---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 4 | 3 | 2 | 1 | |
i-1 | i | ||||||||
1 | 2 | 3 | 4 | 5 | 5 | 4 | 3 | 2 | 1 |
|
|
Manacher Algorithm
Check wiki~ it is O(n)