Problem 196
Longest Palindromic Subsequence
Medium · 20 pts · String, Dynamic Programming
Problem
You are given a string S. A subsequence keeps the order of characters but may skip some of them. Find the length of the longest subsequence of S that is a palindrome, meaning it reads the same forwards and backwards. Let dp[i][j] be the answer for the part of S from position i to position j. If S[i] = S[j], both ends can be used: dp[i][j] = dp[i + 1][j - 1] + 2. Otherwise drop one end: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]). A single character has length 1.
Input
A single string S of lowercase letters.
Output
Print the length.
Constraints
1 <= |S| <= 1000
Example input
bbbab
Example output
4
Explanation
In "bbbab", skipping the a leaves "bbbb", which is a palindrome of length 4. The whole string "bbbab" is not a palindrome, so the answer is 4.