Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 516 Longest Palindromic Subsequence - Walkthrough

LCS with itself

Find the longest palindromic subsequence in ss. observation: LPS(s)(s) = LCS(s,reverse(s))(s, reverse(s)). Why? A palindrome reads the same forwards and backwards.

So the common subsequence between ss and its reverse is palindromic. Example: s="bbbab"s = \text{"bbbab"}. Reverse: "babbb". LCS = "bbbb" with length 44. Alternative: direct DP with dp[i][j]dp[i][j] = LPS of s[i..j]s[i..j]. Transition: if s[i]=s[j]s[i] = s[j], extend; else take max of excluding either end.