Longest Palindromic Subsequence
Implement longestPalindromeSubseq
Given a string
s, find the length of the longest subsequence of it that reads the same forwards and backwards — the characters don't need to be contiguous, just in the same relative order.
The two ends of the string decide everything at each step: if they're equal, both can anchor the palindrome and the problem shrinks to the interval strictly between them, plus 2; if they differ, at least one end has to be left out, so the best answer is whichever of "drop the left end" or "drop the right end" works out better. That's exactly the recurrence for the longest common subsequence between s and its own reverse — but expressing it directly as an interval DP over (i, j) pairs of the same string avoids building a second string entirely, and it's the shape that generalizes cleanly to interval-DP problems beyond palindromes.
Example 1:
Input: s = "bbbab"
Output: 4
Example 2:
Input: s = "cbbd"
Output: 2
Example 3:
Input: s = ""
Output: 0
+ 8 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ s.length ≤ 12 - ●
s consists of lowercase English letters only
s =
bbbab