您的位置:首页 > 其它

最长公共连续子串和最长连续公共子序列

2017-05-21 09:14 246 查看

最长公共连续子序列

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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: