数据结构BF算法的实现全代码 
时间: 2023-05-30 20:06:40 浏览: 52
BF算法,也叫暴力匹配算法,是一种简单粗暴的字符串匹配算法。BF算法的基本思想是,对于主串S和模式串P,从主串S的第一个字符开始,依次与模式串P的每个字符进行匹配,如果匹配失败,则主串S的下一个字符继续与模式串P的第一个字符进行匹配,直到匹配成功或主串S中没有字符可以匹配为止。
下面是BF算法的实现代码:
```
#include <iostream>
#include <cstring>
using namespace std;
int BF(char* s, char* p) {
int slen = strlen(s);
int plen = strlen(p);
for (int i = 0; i <= slen - plen; i++) {
int j;
for (j = 0; j < plen; j++) {
if (s[i + j] != p[j]) {
break;
}
}
if (j == plen) {
return i;
}
}
return -1;
}
int main() {
char s[] = "hello world";
char p[] = "world";
int pos = BF(s, p);
if (pos != -1) {
cout << "匹配成功,位置为:" << pos << endl;
} else {
cout << "匹配失败" << endl;
}
return 0;
}
```
在上面的代码中,BF函数的参数s表示主串,p表示模式串,函数返回值为模式串在主串中的位置,如果匹配失败返回-1。BF函数中的两层循环,第一层循环枚举主串中的每个字符,第二层循环用来匹配模式串和主串中的字符是否相等,如果不相等则退出循环,如果匹配成功,则返回当前位置。
相关推荐
















