最长公共连续子序列
DP求解LCS
用二维数组c[i][j]记录串
x 1 x 2 ⋯x i
x1x2⋯xi与
y 1 y 2 ⋯y j
y1y2⋯yj的LCS长度,则可得到状态转移方程
c[i,j]=⎧ ⎩ ⎨ ⎪ ⎪ 0c[i−1,j−1]+1max(c[i,j−1],c[i−1,j]) i=0 or j=0i,j>0 and x i =y j i,j>0 and x i ≠y j
public static int lcs(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int c[][] = new int[len1+1][len2+1];
for (int i = 0; i <= len1; i++) {
for( int j = 0; j <= len2; j++) {
if(i == 0 || j == 0) {
c[i][j] = 0;
} else if (str1.charAt(i-1) == str2.charAt(j-1)) {
c[i][j] = c[i-1][j-1] + 1;
} else {
c[i][j] = max(c[i - 1][j], c[i][j - 1]);
}
}
}
return c[len1][len2];
}
DP求解最长公共子串
前面提到了子串是一种特殊的子序列,因此同样可以用DP来解决。定义数组的存储含义对于后面推导转移方程显得尤为重要,糟糕的数组定义会导致异常繁杂的转移方程。考虑到子串的连续性,将二维数组 c[i,j] c[i,j]用来记录具有这样特点的子串——结尾为母串 x 1 x 2 ⋯x i x1x2⋯xi与 y 1 y 2 ⋯y j y1y2⋯yj的结尾——的长度。
得到转移方程:
c[i,j]=⎧ ⎩ ⎨ ⎪ ⎪ 0c[i−1,j−1]+10 i=0 or j=0x i =y j x i ≠y j
c[i,j]={0i=0 or j=0c[i−1,j−1]+1xi=yj0xi≠yj
最长公共子串的长度为 max(c[i,j]), i∈{1,⋯,m},j∈{1,⋯,n} max(c[i,j]), i∈{1,⋯,m},j∈{1,⋯,n}
注意点:如果输入的字符串是包含空格的,需要使用gets()输入。#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
char a[55],b[55];
int main(){
gets(a);
gets(b);
int len1=strlen(a);
int len2=strlen(b);
int result=0;
int dp[55][55];
memset(dp,0,sizeof(int));
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
if(i==0 || j==0){
dp[i][j]=0;
}else if(a[i-1]==b[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
result=max(dp[i][j],result);
}else{
dp[i][j]=0;
}
}
}
printf("%d\n",result);
return 0;
}