Overview
A palindrome reads the same forwards and backwards. We use DP to find the longest subsequence that forms a palindrome.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the length of the longest palindromic subsequence in a string by evaluating shrinking boundaries.
A palindrome reads the same forwards and backwards. We use DP to find the longest subsequence that forms a palindrome.
`dp[i][j]` represents the length of the longest palindromic subsequence in the substring `s[i...j]`.
If the boundary characters match (`s[i] == s[j]`), they contribute 2 to the length, plus whatever the longest palindrome is strictly inside them: `2 + dp[i+1][j-1]`.
If they don't match, the longest palindrome must ignore one of the boundaries. It's the max of ignoring `s[i]` or ignoring `s[j]`: `max(dp[i+1][j], dp[i][j-1])`.
| i \ j | 0 (b) | 1 (b) | 2 (b) | 3 (a) | 4 (b) |
|---|---|---|---|---|---|
| 0 (b) | 0 | 0 | 0 | 0 | 0 |
| 1 (b) | 0 | 0 | 0 | 0 | 0 |
| 2 (b) | 0 | 0 | 0 | 0 | 0 |
| 3 (a) | 0 | 0 | 0 | 0 | 0 |
| 4 (b) | 0 | 0 | 0 | 0 | 0 |