BF算法与KMP算法
2014-11-22 19:26
211 查看
#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]); /* else return -1; */ } 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]; /* else return -1; */ } 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; } <span style="font-size:14px;">KMP的改进在于:每当一趟匹配过程中出现字符比较不等时,不需回溯i指针,而是利用已经得到的“部分匹配”的结果将模式向右 “滑动”尽可能远的一段距离后,继续进行比较。 那么需要解决下述问题: 当匹配过程中产生“失配”(即Si≠Pj)时,模式串“向右滑动”可行的距离多远,换句话说,当主串中第i个字符与模式中第j个 字符“失配”时,主串中第i个字符应与模式中哪个字符再比较? j 1 2 3 4 5 6 7 8 a b a a b c a c next 0 1 1 2 2 3 1 2 实际上设next[j] = k,这表明在模式串中存在下列关系: ‘P1……Pk-1’ = ‘Pj-k+1……Pj-1’ 则求next函数值的算法为: </span><pre name="code" class="cpp"><span style="font-size:12px;">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]; } } </span>
相关文章推荐
- 字符串模式匹配的BF算法与KMP算法
- 模式匹配——从BF算法到KMP算法(附完整源码)
- BF算法与KMP算法
- 串匹配问题的BF算法和KMP算法
- 数据结构之字符串匹配算法(BF算法和KMP算法)
- BF算法与KMP算法
- BF算法和KMP算法
- C++实现:BF算法和KMP算法
- 从BF算法到KMP算法(字符串匹配算法)
- string 之 strchr函数 和 strstr函数(BF算法和KMP算法的应用)
- 模式匹配――从BF算法到KMP算法
- 字符串的模式匹配详解--BF算法与KMP算法
- 嵌入式 KMP算法详解及各种应用和BF算法提及
- 字符串模式匹配中BF算法和KMP算法的java实现
- (八)实现了串比较里的BF算法和KMP算法
- c++实现BF算法 KMP算法
- BF算法 + KMP算法
- HDOJ--2087--剪花布条(BF算法和KMP算法都能使用)
- (五)串的模式匹配——BF算法和KMP算法
- BF算法和KMP算法的简介