516. Longest Palindromic Subsequence
- Total Accepted: 10598
- Total Submissions: 24947
- Difficulty: Medium
- Contributors:
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"Output:
4One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"Output:
2
One possible longest palindromic subsequence is "bb".
题解:运用递归的思想,当一个子序列长度为1时,最长回文长度为1,当长度为2时,若两位相等,则最长长度为2,否则为1。
当向一个已知最长回文长度的子序列的两边各加一位时,若两位相等,则最长长度是“只加左边”、“只加右边”、“原长度+2”三种情况的最大值。
若两位不相等,则是“只加左边”、“只加右边”、“原长度”三种情况的最大值。代码如下: