516. Longest Palindromic Subsequence
Problem description:
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: 4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input: “cbbd”
Output: 2
One possible longest palindromic subsequence is “bb”.
Solution1 DFS:
Use a 2D array and two pointers to check longest palindromic subsequence. memo[i][j] means the longest palindromic subsequence on between i
and j
.
example:1
2b b b a b
i j
if s[i] == s[j], the length would increase 2.memo[start][end]= helper(s, start+1, end-1, memo)+2;
1 | b b b a b |
if s[i]!= s[j], the length should be max(memo[i+1][j], memo[i][j-1])
1 | class Solution { |
Solution2 DP:
Similar to previous idea. Use a pointer i
to denote the length that we traverse right now. Another pointer j
to denote check the palindromic substring.
example:1
2b b b a b
j i
dp[i][j]= dp[i-1][j+1]+2
1 | b b b a b |
dp[i][j]= max(dp[i-1][j], dp[i][j+1])
1 | class Solution: |
1 | class Solution { |
reference: