7. (18 points) A palindrome is a string that reads the same from the left and from the right. For example, REDDER, I, ROTATOR, MOM, are palindromes. From a non-palindrome string, you can always remove an arbitrary number of characters from it to make it a palindrome. For example, from both ADAM and ADMA, you can remove 'M' to obtain a palindrome, ADA. In both cases, we say that ADA is the longest palindrome subsequence in the original strings, ADAM and ADMA.
We would like to derive a dynamic programming algorithm to determine the length of the longest palindrome subsequence in a string. You are given the string \(S\) of length \(n\) in the form of a character array \(S=s[\,]\), where \(s[i]\) is the \(i\)-th character in the string, \(1\le i\le n\).
(a) (12 points) As the first step, please complete the following equation to represent the length of the longest palindrome subsequence in the given string \(S\) by filling out the blanks. \(L(i,j)\) represents the length of the longest palindrome subsequence in \(s[i..j]\), a substring of \(S\) that starts from the \(i\)-th character and ends at the \(j\)-th character of \(S\). \(L(i,j)\) is defined for \(1\le i\le n\), \(1\le j\le n\), \(j\ge i-1\), and
\(L(i,j)=\begin{cases}\underline{\ \ (1)\ \ }&,\text{ if }i=j+1\\\underline{\ \ (2)\ \ }&,\text{ if }i=j\\\underline{\ \ (3)\ \ }&,\text{ if }i\lt j\text{ and }s[i]==s[j]\\\underline{\ \ (4)\ \ }&,\text{ otherwise.}\end{cases}\)
(b) (6 points) Calculate the length of the longest palindrome sequence in the string CABDAACBADFA.
(a) \(i=j+1\):空字串 → (1) \(0\)
\(i=j\):一個字元本身就是 palindrome → (2) \(1\)
\(s[i]=s[j]\):兩端接在 \(s[i+1..j-1]\) 的最長 palindrome 兩邊 → (3) \(L(i+1,j-1)+2\)
\(s[i]\ne s[j]\):兩端不可能同時用,至少丟掉一個 → (4) \(\max\{L(i+1,j),\ L(i,j-1)\}\)
(1) \(0\) (2) \(1\) (3) \(L(i+1,j-1)+2\) (4) \(\max\{L(i+1,j),L(i,j-1)\}\)
(b) \(n=12\),依 \(j-i\) 由小到大填 \(L(i,j)\):
\(L(1,12)\):\(s[1]=\)C,\(s[12]=\)A 不同 → \(\max\{L(2,12),L(1,11)\}\);\(L(2,12)\):\(s[2]=s[12]=\)A → \(L(3,11)+2=5+2=7\)
一個長度 7 的 palindrome subsequence:ADABADA(位置 2、4、5、8、9、10、12)
\(L(1,12)=7\)