经典算法之暴力匹配算法(字符串)

来源:互联网 发布:新材料在线软件 编辑:程序博客网 时间:2024/05/20 18:42
/************************author's email:wardseptember@gmail.comdate:2017.12.17暴力匹配算法************************//*对于一个串中的某子串的定位操作称为串的模式匹配,其中待定位的子串称为模式串。算法的基本思想:从主串的第一个位置起和模式串的第一个字符开始比较,如果相等,则继续逐一比较后续字符;否则从主串的第二个字符开始,再重新用上一步的方法与模式串做比较,以此类推,直到比较完模式串中的所有字符。若匹配成功,则返回模式串在主串中的位置;若匹配不成功,则返回一个可区别与主串的位置标记,如“-1”。*/#include<iostream>#include <stdio.h>using namespace std;#define maxSize 50int BF(char *str, char *substr);//暴力匹配算法void main() {    char str[50] = "ABABCABCACBAB";    char substr[50] = "ABCAC";    int result;    cout << "BF算法匹配结果:" << endl;    result = BF(str, substr);    if (result != -1)        cout << "主串与子串在主串的第" << result << "个字符(首字符的位置为0)处首次匹配" << endl;    else        cout << "无匹配子串" << endl;}int BF(char *str, char *substr) {//暴力匹配算法    int i = 0, j = 0, k = i;    while (i < strlen(str) && j < strlen(substr)) {        if (str[i] == substr[j]) {            ++i;            ++j;        }        else {            j = 0;            i = ++k;//匹配失败,i从主串的下一位置开始,k中记录了上一次的起始位置        }    }    if (j >= strlen(substr)) {        return k;    }    else        return -1;}

以上如有错误,请指出,大家共同学习进步

阅读全文
0 0
原创粉丝点击