【数据结构基础】串的模式匹配-BF算法

#include
#pragma warning(disable:4996)//兼容vs中使用scanf
#define Maxsize 20
int StrIndex_BF(char *s, char *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]+ 1) {
        return (i - t[0]);
    }
    else {
        return -1;
    }
}
char* ReadStr(char *s1) {
    int i, length;
    scanf("%d\n", &length);
    s1[0] = length;
    for (i = 1; i <= s1[0]; i++) {
        s1[i] = getchar();
    }
    s1[i] = '\0';
    return s1;
}
int main(void) {
    char Str1[Maxsize], Str2[Maxsize], *p, *q;
    int index;
    p = ReadStr(Str1);
    q = ReadStr(Str2);
    index = StrIndex_BF(p, q);
    if (index == -1) {
        printf("Not Find");
    }
    else {
        printf("%d\n", index);
    }
    return 0;
}

【数据结构基础】串的模式匹配-BF算法_第1张图片

你可能感兴趣的:(数据结构和算法)