[算法导论] BF算法与KMP算法
来源:互联网 发布:事情进度跟踪软件 编辑:程序博客网 时间:2024/06/06 13:02
#include <iostream>#include <cstring>using namespace std;int Index_BF(char *s,char *t)//从串s的第一个字符开始找首次与串t相等的子串 {int i=1,j=1;while((i<=s[0])&&(j<=t[0])){ if(s[i]==t[j]) { i++; j++; } else { i = i-j+2; j=1; } if(j>t[0]) return (i-t[0]);} return -1;}void GetNext(char *t,int next[])//求模式t的NEXT值并存入NXET数组中 { int i = 1,j = 0;next[1] = 0;while( i < t[0] ){while( (j>0)&&(t[i]!=t[j]) ) j = next[j]; i++; j++; if(t[i]==t[j]) next[i] = next[j]; else next[i] = j;}}int Index_KMP( char *s,char *t,int pos,int next[] )//从串s的第pos个字符开始找首次与串t相等的子串。 { int i = pos;int j = 1;while( (i<=s[0])&&(j<=t[0]) ) if(j==0||s[i]==t[j]){ i++; j++; } else j = next[j];//回溯 if(j>t[0]) return i-t[0];}int main(){char s[100];char t[100];int next[100]; int n,m,l1,l2;gets(s);gets(t);l1<span style="font-size:12px;"> = strlen(s);s[0]=l1-1;</span>l2 = strlen(t);t[0]=l2-1;n = Index_BF(s,t);cout << n << endl;GetNext(t,next); m = Index_KMP(s,t,1,next);cout << m << endl;return 0;}KMP的改进在于:每当一趟匹配过程中出现字符比较不等时,不需回溯i指针,而是利用已经得到的“部分匹配”的结果将模式向右“滑动”尽可能远的一段距离后,继续进行比较。那么需要解决下述问题:当匹配过程中产生“失配”(即Si≠Pj)时,模式串“向右滑动”可行的距离多远,换句话说,当主串中第i个字符与模式中第j个字符“失配”时,主串中第i个字符应与模式中哪个字符再比较?j 1 2 3 4 5 6 7 8 a b a a b c a cnext 0 1 1 2 2 3 1 2实际上设next[j] = k,这表明在模式串中存在下列关系:‘P1……Pk-1’ = ‘Pj-k+1……Pj-1’则求next函数值的算法为:void Get_next(SString T,int next[]){//求模式串T的next函数值并存入数组next。int i = 1;next[1] = 0;int j = 0;while(i < T[0])//T[0]存储该模式串长度 {if(j==0||T[i]==T[j]){++i;++j;next[i] = j; }else j = next[j];} }
0 0
- [算法导论] BF算法与KMP算法
- BF与KMP算法
- Kmp 与 BF算法
- BF算法与KMP算法
- BF算法与KMP算法
- KMP算法与BF算法
- BF算法与KMP算法
- BF和KMP算法
- KMP算法 bf
- BF和KMP算法
- BF算法和KMP算法
- BF算法和 KMP 算法
- BF算法和KMP算法
- [数据结构与算法]BF算法与KMP算法实现
- 字符串匹配算法 BF算法与KMP算法
- KMP与BF模式匹配算法
- 字符串模式匹配的BF算法与KMP算法
- 【数据结构与算法】字符串匹配之BF&KMP算法
- CSU 1339: 最后一滴血(模拟啊 湖南省第九届大学生计算机程序设计竞赛)
- VIM使用技巧1
- Yale开放课程博弈论20
- tomcat通过conf-Catalina-localhost目录发布项目详解
- 第十三周 项目四--数组的排序(1)对数字排序
- [算法导论] BF算法与KMP算法
- Android数据存储
- js四舍五入小数
- 遇到一个numpy 错误
- 保时捷停街边遭砸爆玻璃 小偷偷走3件衣服
- C# 连接 Mysql 中文乱码问题
- MySQL concat函数的使用
- c语言:高级指针话题
- Oracle Advanced Pricing White Papers