求2个字符串的最长公共子串——矩阵法
来源:互联网 发布:奔腾楚天激光机编程 编辑:程序博客网 时间:2024/06/01 10:05
有2个字符串,求它们的最长的公共子串,不是公共子序列,要连续。
例如:str1=“abcabce",str2="bcacabcgef",那么最长的公共子串为”cabc“。
最直观的办法是用矩阵法,累计记录最长子串的长度和位置。
int hjd_longest_common_substr(char *str1, char *str2, char *strresult){ int lcs_len=0, mx=0, my=0; int nlen1 = strlen(str1), nlen2 = strlen(str2); *strresult = '\0'; int AR[nlen2][nlen1]; int x=0, y=0; for(y=0; y<nlen2; y++) for(x=0; x<nlen1; x++) { AR[y][x]=0; } for(y=0;y<nlen2;y++) { for(x=0;x<nlen1;x++) { if(*(str1+x)==*(str2+y)) { if((x==0)||(y==0)) { AR[y][x] = 1; } else { AR[y][x] = AR[y-1][x-1] + 1; } if (AR[y][x]>lcs_len) { //记录最长子串的长度和结束的位置 lcs_len=AR[y][x]; mx=x; my=y; } } } } if(lcs_len>0) { int i=0; for(i=0;i<lcs_len;i++) { *(strresult+i) = *(str1 + mx - AR[my][mx] + 1 + i); printf("%c\t", *(str1 + mx - AR[my][mx] + 1 + i)); } *(strresult + i) = '\0'; } return(lcs_len);}测试正确。
0 0
- 求2个字符串的最长公共子串——矩阵法
- 求2个字符串的最长公共子串长度
- 每天一道算法题(5)——求2个字符串的最长公共子序列和最长公共子字符串
- sdut 1008 最大公共子串(求n个字符串的最长公共子串)
- hdu1403---Longest Common Substring(后缀数组求2个字符串的最长公共子串)
- 华为上机题:求N个字符串的最长公共子串,字符串长度不超过255。
- sdut 1008 最大公共子串(求n个字符串的最长公共子串)lcs
- 求两个字符串的最长公共子串——Java实现
- 练习54-求N个字符串的最长公共子串
- 求两个字符串的最长公共子串,最长公共子序列,编辑距离
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长的连续公共子串
- 求两个字符串的最长公共子串的长度
- 求两个字符串的最长公共子串的长度
- 求两个字符串最长公共子串
- VB6求两个字符串最长公共子串的问题
- JDK源码阅读——Collection
- 玩转快速排序
- Problem G
- Qt-----反射机制
- 刚刚涉及IT领域的大三汪的小心思(第一篇博客)
- 求2个字符串的最长公共子串——矩阵法
- ldd gperftool 用法
- 使用Consul快速搭建简易分布式服务监控系统
- mysql基本操作
- 编程血泪史之前端
- git osc 体验
- mysql连接问题
- 7对数字排序
- FEDay第二届前端开发者大会后记