最长公共子序列(二)
拆分为两步
1.先计算最长序列的长度
2.倒推最长序列
考虑是序列 因此定义数组dp[strlen(s1)+1][strlen(s2)+1]
分别存储s1.s2每个字符下的最长序列长度;
考虑两种情况
1.*s1==*s2
转移方程
dp[i][j] = dp[i - 1][j - 1] + 1;
2.*s1!=*s2
dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
取前一个字符下长度最大值
char* LCS(char* s1, char* s2 ) {
int m = strlen(s1), n = strlen(s2);
int dp[m + 1][n + 1];
memset(dp, 0, sizeof(dp));
int p=0;
int i;
int j;
for (i = 1; i <= m; i++) {
char c1 = s1[i - 1];
for (j = 1; j <= n; j++) {
char c2 = s2[j - 1];
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
//dp[i][j] = fmax(dp[i - 1][j], dp[i][j - 1]);
dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
}
}
}
if(dp[m][n]==0)
return "-1";
int len=dp[m][n];
char *res=(char *)malloc(len+1);
res[len--]='\0';
i--;
j--;
while(i!=0&&j!=0)
{
if(dp[i][j]>dp[i][j-1]&&dp[i][j]>dp[i-1][j])
{
res[len--]=s1[i-1];//从后往前填入序列
i--;
j--;
}
else if (dp[i][j]==dp[i][j-1]&&dp[i][j]>dp[i-1][j])
{
j--;
}
else if (dp[i][j]==dp[i-1][j]&&dp[i][j]>dp[i][j-1])
{
i--;
}
else
{
i--;
j--;
}
}
return res;
}
最长公共子串
定义数组dp[strlen(s1)+1][strlen(s2)+1]
分别存储s1.s2每个字符下的最长子串长度;
转移方程:
*s1==*s2时 dp[i][j]=dp[i-1][j-1]+1;
pos为当前最长子串最后一位字符位置
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*
* C语言声明定义全局变量请加上static,防止重复定义
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
char* LCS(char* str1, char* str2 ) {
// write code here
char *res;
int len1=strlen(str1);
int len2=strlen(str2);
int dp[len1+1][len2+1];
memset(dp, 0, sizeof(dp));
int max=0;
int pos=0;
int i,j;
for(i=1;i<=len1;i++)
{
int c1=str1[i-1];
for(j=1;j<=len2;j++)
{
int c2=str2[j-1];
if(c1==c2)
{
dp[i][j]=dp[i-1][j-1]+1;
}
else
{
dp[i][j]=0;
}
if(max<dp[i][j])
{
max=dp[i][j];
pos=i-1;
}
}
}
printf("%c",str1[pos]);
pos=pos-max+1;
res=(char*)malloc(max+1);
memcpy(res, str1+pos,max);
res[max]='\0';
return res;
}
int LIS(int* arr, int arrLen ) {
// write code here
int dp[arrLen+1];
for(int i=0;i<arrLen;i++)
dp[i]=1;
int res=0;
for(int i=1;i<arrLen;i++)
{
for(int j=0;j<i;j++)
{
if(arr[i]>arr[j]&&dp[i]<dp[j]+1)
{
dp[i]=dp[j]+1;
res=fmax(res,dp[i]);
}
}
}
return res;
}