KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am trying to solve a dynamic programming problem from Cormem's Introduction to Algorithms 3rd edition (pg 405) which asks the following: A palindrome is a nonempty string over some alphabet that reads the same forward and backward. Examples of palindromes are all strings of length 1, civic , racecar , and aibohphobia (fear of palindromes). Give an efficient algorithm to find the longest palindrome that is a subsequence of a given input string. For example, given the input character , your algorithm should return carac . Well, I could solve it in two ways: First solution: The Longest Palindrome Subsequence (LPS) of a string is simply the Longest Common Subsequence of itself and its reverse. (I've build this solution after solving another related question which asks for the Longest Increasing Subsequence of a sequence). Since it's simply a LCS variant, it also takes O(n²) time and O(n²) memory. Second solution: The second solution is a bit more elaborated, but also follows the general LCS template. It comes from the following recurrence: lps(s[i..j]) = s[i] + lps(s[i+1]..[j-1]) + s[j], if s[i] == s[j]; max(lps(s[i+1..j]), lps(s[i..j-1])) otherwise The pseudocode for calculating the length of the lps is the following: compute-lps(s, n): // palindromes with length 1 for i = 1 to n: c[i, i] = 1 // palindromes with length up to 2 for i = 1 to n-1: c[i, i+1] = (s[i
Tags (comma-separated)
Save Edits
Cancel