跳到主要內容

Longest Palindromic Subsequence

Our goal is to find the longest palindromic subsequence in a given sequence. For example, we are given a sequence "ABCBAD". The longest palindromic subsequence is "ABCBA". Now let $s$ is the given sequence  and we use $s[i]$ to denote the $i^\text{th}$ character in $s$. In addition, we let $L[i, j]$ denote the length of longest palindromic subsequence in $s[i:j]$ (from $s[i]$ to $s[j]$). If $s[i:j]$ is palindromic, then the front character $s[i]$ and the last character $s[j]$ should be the same. We can also say that:
$$L[i, j] = L[i+1, j-1] + 2$$
On the other hand, if $s[i:j]$ is not palindromic (or, $s[i]\neq s[j]$), then:
$$L[i, j] = max(L[i+1, j], L[i, j-1])$$
We can follow this rule to solve this problem recursively. First, we can consider the longest palindromic subsequence when $i=j$:


Because the length of $s[i:j]$ is 1, $L[i, j]=1$. Next, we consider $j = i+1$. $L[i, j]$ will be 2 only when $s[i]=s[j]$; otherwise, $L[i, j]=1$.


Next $j = i+2$ is considered. We can determine the value of $L[i, j]$ through the rules we just mentioned:


We can observe that when $i=1, j=3$, $s[i]=s[j]$, and thus $L[1, 3]=L[2, 2]+2=3$. We can repeatedly apply this process until $L[5, 5]$ is obtained:




We can create another table to store the $(i, j)$ index pair in the same way in order to obtain the sequence "ABCBA". Note that the time complexity of this algorithm is $O(n^2)$ and the space complexity is $O(n^2)$ as well.

留言

這個網誌中的熱門文章

Heap Sort

Heap sort is one of traditional sorting algorithms with time complexity $\mathcal{O}(n\ln n)$. After reading this article, you will be able to build a left-justified binary tree and implement heap sorting algorithm. We first defined some terms that will be used later.  Definition  (Balanced tree) A binary tree of depth $n$ is balanced if all the nodes at depth $0$ through $n-2$ have two children.  That is, for any two leaves in the tree the difference is at most 1. We can see some examples for balanced trees and imbalanced trees.  Definition  (Left-justified binary tree)   A binary tree is left-justified if all the leaves are at the same depth and all the leaves at depth $n+1$ are to the left of all nodes at depth $n$. The following figures illustrates the left justified tree: In order to implement heap sorting algorithm, we should first build a binary max-heap (min-heap) tree which is a left-justified balanced tree and whose pa...