String 给定一个字符串X和该字符串的倒数,Y。X和Y的最长公共序列总是回文吗?

String 给定一个字符串X和该字符串的倒数,Y。X和Y的最长公共序列总是回文吗?,string,algorithm,lcs,String,Algorithm,Lcs,我们的教授给了我们以下问题: Input A sequence of characters X = x1, x2, ... ,xn Output The length of the longest sub-sequence of X that is a palindrome 我的解决办法是: Take X and reverse it into the sequence Y = y1, y2, ... , yn Then perform LongestCommonSubsequ

我们的教授给了我们以下问题:

Input
   A sequence of characters X = x1, x2, ... ,xn
Output
   The length of the longest sub-sequence of X that is a palindrome
我的解决办法是:

 Take X and reverse it into the sequence Y = y1, y2, ... , yn
 Then perform LongestCommonSubsequence(X,Y)  
他给了我一部分学分然后写了

"The LCS of X and reverse X is not necessarily a palindrome."
但我一直在运行这个算法(顺便说一句,不是我的),用X和反向X,我得到的只是回文

/**
 ** Java Program to implement Longest Common Subsequence Algorithm
 **/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/** Class  LongestCommonSubsequence **/
public class  LongestCommonSubsequence
{    
/** function lcs **/
public String lcs(String str1, String str2)
{
    int l1 = str1.length();
    int l2 = str2.length();

    int[][] arr = new int[l1 + 1][l2 + 1];

    for (int i = l1 - 1; i >= 0; i--)
    {
        for (int j = l2 - 1; j >= 0; j--)
        {
            if (str1.charAt(i) == str2.charAt(j))
                arr[i][j] = arr[i + 1][j + 1] + 1;
            else 
                arr[i][j] = Math.max(arr[i + 1][j], arr[i][j + 1]);
        }
    }

    int i = 0, j = 0;
    StringBuffer sb = new StringBuffer();
    while (i < l1 && j < l2) 
    {
        if (str1.charAt(i) == str2.charAt(j)) 
        {
            sb.append(str1.charAt(i));
            i++;
            j++;
        }
        else if (arr[i + 1][j] >= arr[i][j + 1]) 
            i++;
        else
            j++;
    }
    return sb.toString();
}
}
/**
**实现最长公共子序列算法的Java程序
**/
导入java.io.BufferedReader;
导入java.io.InputStreamReader;
导入java.io.IOException;
/**类最长公共子序列**/
公共类最长公共子序列
{    
/**功能lcs**/
公共字符串lcs(字符串str1、字符串str2)
{
int l1=str1.length();
int l2=str2.length();
int[]arr=新int[l1+1][l2+1];
对于(int i=l1-1;i>=0;i--)
{
对于(int j=l2-1;j>=0;j--)
{
if(str1.字符(i)=str2.字符(j))
arr[i][j]=arr[i+1][j+1]+1;
其他的
arr[i][j]=Math.max(arr[i+1][j],arr[i][j+1]);
}
}
int i=0,j=0;
StringBuffer sb=新的StringBuffer();
而(i=arr[i][j+1])
i++;
其他的
j++;
}
使某人返回字符串();
}
}

我如何证明或反驳X和X的倒数X的最长公共子序列是或不是回文序列

对于
X=0,1,2,0,1
我们有
Y=reverse(X)=1,0,2,1,0
,最长的子序列之一是
0,2,1
。所以你的建议不符合一般情况。但问题中给出的算法返回的LCS始终可能是回文。在我的示例中,所有LCS-s的系统枚举如下:
0,1,0
0,2,1
0,2,0
1,2,0
1,2,1
1,0,1
,第一个LCS确实是回文。但我还不能大体证明。所以我认为,实际上(教授和你)都是对的:虽然可以有
X
reverse(X)
的LCS不是回文,但LCS算法的大多数(实际上:直接)实现总是会为
X
reverse(X)
返回回文。(仍然缺少完整的证据)

这个链接可能会有所帮助:扰流板:LCS不一定输出回文。@coproc我认为Tymur的链接提供了一个反例,请阅读这里的@•㪞עבקן好的,对。尽管如此,我仍然认为OP的LCS算法总是会返回一个回文(另请参见我的答案)。@TymurGubayev因为要求输出最长公共子序列的长度,所以如果有其他LCS与最长回文一样长,也可以。FWIW,我认为你是对的,你发布的算法总是输出回文。我写了一个快速的程序来测试每个不同长度的字符串(直到同构)的假设