class Solution
{
public int[][] LCSLength(char []a, char []b)
{
int lenA = a.length;
int lenB = b.length;
int [][]dp = new int[lenA+1][lenB+1];
int [][]flag = new int[lenA+1][lenB+1];
for(int i=1; i<=lenA; i++)
{
for(int j=1; j<=lenB; j++)
{
if(a[i-1] == b[j-1])
{
dp[i][j] = dp[i-1][j-1]+1;
flag[i][j] = 1;
}
else if(dp[i-1][j] >= dp[i][j-1])
{
dp[i][j] = dp[i-1][j];
flag[i][j] = 2;
}
else
{
dp[i][j] = dp[i][j-1];
flag[i][j] = 3;
}
}
}
return flag;
}
public String LCS(char []a, int i, int j, int [][]flag)
{
if(i==0 || j==0) return "";
if(flag[i][j] == 1) return LCS(a, i-1, j-1, flag) + a[i-1];
else if(flag[i][j] == 2) return LCS(a, i-1, j, flag);
else return LCS(a, i, j-1, flag);
}
}
最长公共子序列
最新推荐文章于 2024-07-20 22:14:11 发布