#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "string.h"
#define N 100
int lcsLength(char *x, char *y, int lenx, int leny, int z[N][N], int b[N][N])
//返回字符串a和b的最长公共子串长度
//lenx为字符串x的长度,leny为子串y的长度
//z[i][j]记录字符串a[i]、b[j]最长公共子串长度
//b[i][j]记录c[i][j]的值是由哪个子问题得到(3种情况之一),构造最长公共子序列时用到
{
int i, j;
for(i=1; i<=leny; i++)
z[0][i] = 0; //当子串a为空时,最长公共子串长度为0
for(i=1; i<=lenx; i++)
z[i][0] = 0; //当子串b为空时,最长公共子串长度为0
for(i=1; i<=lenx; i++) //自下而上计算子问题
for(j=1; j<=leny; j++)
{
if(x[i] == y[j]) //情况1
{
z[i][j] = z[i-1][j-1] + 1;
b[i][j] = 1;
}
else if(z[i-1][j] >= z[i][j-1]) //情况2
{
z[i][j] = z[i-1][j];
b[i][j] = 2;
}
else //情况3
{
z[i][j] = z[i][j-1];
b[i][j] = 3;
}
}
return z[lenx][leny];
}
void lcs(int i, int j, char x[N], int b[N][N]) //构造公共子序列
{
if(i==0 || j==0) return;
/*第1种情况下,X(i)和Y(j)的最长公共子序列由X(i-1)和
Y(j-1)的解LCS(i-1, j-1, x, b),加上位于最后的X[i]组成
*/
else if(b[i][j]==1)
{
lcs(i-1,j-1,x,b);
printf("%c", x[i]);
}
//其它2种情况下,原问题等于子问题解
else if(b[i][j]==2)
lcs(i-1,j,x,b);
else
lcs(i,j-1,x,b);
}
int main()
{
char x[N], y[N];
gets(x);
gets(y);
int lenx = strlen(x);
int leny = strlen(y);
int i;
for(i=lenx; i>0; i--)
x[i] = x[i-1];
for(i=leny; i>0; i--)
y[i] = y[i-1];
int z[N][N], b[N][N];
int length = lcsLength(x, y, lenx, leny, z, b);
printf("最长公共长度为:%d\n", length);
lcs(lenx, leny, x, b);
printf("\n");
return 0;
}
LintCode
最长公共子序列
给出两个字符串,找到最长公共子序列(LCS),返回LCS的长度。
样例
给出”ABCD” 和 “EDCA”,这个LCS是 “A” (或 D或C),返回1
给出 “ABCD” 和 “EACB”,这个LCS是”AC”返回 2`
class Solution {
public:
/**
* @param A: A string
* @param B: A string
* @return: The length of longest common subsequence of A and B
*/
int longestCommonSubsequence(string &A, string &B) {
// write your code here
int nA = A.size();
int nB = B.size();
if(nA == 0 || nB == 0)
{
return 0;
}
vector<vector<int> > dp(nA, vector<int>(nB, 0));
for(int i=0; i<nB; i++)
{
if(A[0] == B[i])
dp[0][i] = 1;
}
for(int i=0; i<nA; i++)
{
if(A[i] == B[0])
dp[i][0] = 1;
}
for(int i=1; i<nA; i++)
{
for(int j=1; j<nB; j++)
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
if(A[i] == B[j] && dp[i][j] < dp[i-1][j-1] + 1)
dp[i][j] = dp[i-1][j-1] + 1;
}
}
return dp[nA-1][nB-1];
}
};
最长公共子串
给出两个字符串,找到最长公共子串,并返回其长度。
样例
给出A=“ABCD”,B=“CBCE”,返回 2
挑战
O(n x m) time and memory.
class Solution {
public:
/**
* @param A: A string
* @param B: A string
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
int nA = A.size();
int nB = B.size();
if(nA == 0 || nB == 0)
return 0;
vector<vector<int> > dp(nA, vector<int>(nB, 0));
int maxLen = 0;
for(int i=0; i<nA; i++)
{
if(A[i] == B[0])
{
dp[i][0] = 1;
maxLen = 1;
}
}
for(int i=0; i<nB; i++)
{
if(A[0] == B[i])
{
dp[0][i] = 1;
maxLen = 1;
}
}
for(int i=1; i<nA; i++)
{
for(int j=1; j<nB; j++)
{
if(A[i] == B[j])
{
dp[i][j] = max(dp[i][j], dp[i-1][j-1] + 1);
maxLen = max(maxLen, dp[i][j]);
}
}
}
return maxLen;
}
};