串——BF算法(匹配子串)

#include<iostream>
#include <cstring>
using namespace std;

#define MAXLEN 255

/*
BF算法,匹配子串
*/

typedef struct{
    char ch[MAXLEN+1];
    int length;
}SString;

string StrAssign(SString &S,string e){
    strcpy(S.ch,e.c_str());
    S.length = e.length();
    for(int i=S.length;i>0;i--){
        S.ch[i] = S.ch[i-1];
    }
    return "OK";
}


int Index_BF(SString S,SString T){    //返回匹配成功的开始位置
int i,j ;
    i = j = 1;
    while(i <= S.length && j <= T.length ){
        if( S.ch[i] == T.ch[j] ) {++i;++j;}
        else
        {
            i = i-j+2;j=1;
        }
    }
    if(j > T.length) return i-T.length;
    else return 0;

}

int main(){

    SString S , T;
    StrAssign(S,"ababcabcacbab");
    StrAssign(T,"abcac");
    cout << Index_BF(S,T)<<endl;


    system("pause");
    return 0;
}

 时间复杂度  (n为主串长度,m为子串长度)

最好情况:在子串第一个就匹配错误:O(n+m)

最坏情况:在子串最后一个才匹配错误:O(n*m)

原文地址:https://www.cnblogs.com/LuMinghao/p/14015208.html