求两个字符串的最长公共子串(包括连续和非连续)
2013-08-20 15:03
316 查看
典型的动态规划问题,非连续有点问题。
#include <stdlib.h> #define N 100 int c ; int dp[N+5][N+5]; char* a="hijdefg"; char* b ="hfghijc"; int LCS(char* a, int aLen, char* b, int bLen){ int maxLen = 0; int pos = 0; int i = 0, j = 0; for(; i < aLen; i++){ for(j = bLen; j >= 0; j--){ if(a[i] == b[j - 1]){ c[j] = c[j - 1] + 1; if(c[j] > maxLen){ maxLen = c[j]; pos = j - 1; } }else{ c[j] = 0; } } } for(i = maxLen-1; i >= 0; i--){ printf("%c ",b[pos - i]); } return maxLen; } int NonContinousLCS(char* a, int aLen, char* b, int bLen){ int i = 1, j = 1; for(; i < aLen; i++){ dp[i][0] = 0; dp[0][i] = 0; } for(; i <= aLen; i++){ for(; j <= bLen; j++){ if(a[i - 1] == b[j - 1]){ dp[i][j] = dp[i-1][j-1] + 1; }else{ dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } } return dp[aLen][bLen]; } int max(int a, int b){ return a >= b ? a : b; } int main(){ LCS(a,8,b,8); int result = NonContinousLCS(a,8,b,8); printf("max len: %d",result); getchar(); }
相关文章推荐
- 两个字符串的最长连续公共子串
- 问题:求两个字符串的最长公共子串。 要求:输入两个字符串,输出它们的最长公共子串,包括长度。 设计: 设计一个类 String,包括一个 len(字符串长度)和字符串指针 s。另有如下成员函数: ·
- 求两个字符串的最长的连续公共子串
- 两个字符串的最长公共子串(子串为连续的)
- 求两个字符串的最长的连续公共子串
- 问题:求两个字符串的最长公共子串。 要求:输入两个字符串,输出它们的最长公共子串,包括长度。
- 多个字符串的公共最长连续子串(对两个字符串的扩展)
- 求两个字符串的最长的连续公共子串
- 字符串操作:两个字符串的最长连续公共子串
- 两个字符串的最长连续公共子串
- 求两个字符串的最长的连续公共子串和求两个字符串的公共子序列
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串(按位异或法)
- 两个字符串的最长连续公共子串
- 求两个字符串的(连续的)最长公共子串
- 求两个字符串的最长连续公共子串
- 华为(8)查找两个字符串a,b中的最长公共子串
- 查找两个字符串a,b中的最长公共子串
- poj 2774 求两个字符串的最长公共子串
- 求两个字符串的最长公共子串的长度