最长公共连续子串和最长连续公共子序列
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 jpublic 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;}相关文章推荐
- 最长递增子序列(nlogn),最长公共子串(连续),最长公共子序列(不连续)
- 求两个字符串的最长的连续公共子串和求两个字符串的公共子序列
- 最大子序列、最长连续公共子串(连续)、最长公共子序列(动态规划)
- 动态规划求解最长公共子串与公共子序列
- 字符串题目-最长的公共连续子串
- 最长公共子序列|最长公共子串|最长重复子串|最长不重复子串|最长回文子串|最长递增子序列|最大子数组和
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- POJ 3080 Blue Jeans(KMP:最长连续公共子序列)
- URAL 1517. Freedom of choice(后缀数组:最长公共连续子串)
- 如何求最长连续公共子序列和最长连续子字符串
- 最长公共子串(子序列)、最长递增子序列、最长回文子串等问题
- 多个字符串的公共最长连续子串(对两个字符串的扩展)
- 最长连续公共子串
- 如何求最长连续公共子序列和最长连续子字符串
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- LongestCommonSequence 最长连续公共子序列(算法导论是最长公共子序列)
- 最长连续公共子序列
- 最大子序列、最长公共子串、最长公共子序列
- poj1458(DP最长连续公共子序列)
- 牛客模拟二:最长公共连续子串