我的公共子字符串查找方法,非递归实现或者可以说没有实现递归
2013-11-28 16:50
239 查看
参考文章地址如下:/article/1422815.html
子字符串的定义和子序列的定义类似,但要求是连续分布在其他字符串中。比如输入两个字符串BDCABA和ABCBDAB的最长公共字符串有BD和AB,它们的长度都是2。
Substring可以用动态规划解决,令 c[i][j]表示Xi和Yi的最大Substring的长度,比如
X = <y, e, d, f>
Y = <y, e, k, f>
c[1][1] = 1
c[2][2] = 2
c[3][3] = 0
c[4][4] = 1
动态转移方程为:
如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1
如果xi ! = yj, 那么c[i][j] = 0
代码如下:
子字符串的定义和子序列的定义类似,但要求是连续分布在其他字符串中。比如输入两个字符串BDCABA和ABCBDAB的最长公共字符串有BD和AB,它们的长度都是2。
Substring可以用动态规划解决,令 c[i][j]表示Xi和Yi的最大Substring的长度,比如
X = <y, e, d, f>
Y = <y, e, k, f>
c[1][1] = 1
c[2][2] = 2
c[3][3] = 0
c[4][4] = 1
动态转移方程为:
如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1
如果xi ! = yj, 那么c[i][j] = 0
代码如下:
#include <stdio.h> #include <string.h> int comm_str(char * str1, char * str2) { int i, j, k, max, x, y; const int len1 = strlen(str1); const int len2 = strlen(str2); int c[len1][len2]; for(i = 0; i < len1+1; i++) for(j = 0; j < len2+1; j++) c[i][j] = 0; max = -1; for(i = 1; i < len1; i++) { k = 0; for(j=1; j < len2; j++) { if(str1[i-1+k] == str2[j-1]) { c[i+k][j]=c[i-1+k][j-1]+1; if(c[i+k][j]>max) { max=c[i+k][j]; x=i+k; y=j; } k++; } else c[i+k][j]=0; } } char s[10000]; k=max; i=x-1, j=y-1; s[k--]='\0'; while(i>=0 && j>=0 && k >= 0) { if(str1[i]==str2[j]) { s[k--]=str1[i]; i--; j--; } else break; } printf("most longest common str:"); puts(s); return max; } int main() { char str1[10000], str2[10000]; puts("please input first string:"); gets(str1); puts("please input second string:"); gets(str2); printf("the length of longest common substring is %d\n",comm_str(str1, str2)); }执行结果如下:
相关文章推荐
- SQL连接(左连接、右连接、全连接)
- C语言 字符串处理函数 转自 http://blog.chinaunix.net/uid-25885064-id-3175049.html
- TCP传输连接有限状态机转换机制
- 【转】软件测试工具LoadRunner中运行QTP脚本
- linux iostat命令详解
- linux usb core
- I2C不通的分析思路
- mysql 确定前缀索引长度方法
- python模块导入机制
- C++冒泡排序模板
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- windows8.1轻松创建和打印3D对象即三维物体
- java.sql.SQLException: ORA-00911: invalid character
- oracle单表删除重复数据
- vs2012和vs2010同时安装冲突
- ios 僵尸调试
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- Android基础类之BaseAdapter
- Response already committed; the authentication mechanism must be able to modify buffer size
- 工厂模式(Factory)