串的模式匹配

串的模式匹配(待完善)

// Created by louie on 2022/10/7.
//
#include <stdio.h>
#define MAXSIZE 100010
typedef struct {
    char str[MAXSIZE];
    int length;
}String;
void Init(String *S){
    S->length = 0;
    for (int i = 0; i < MAXSIZE; ++i) {
        S->str[i] = '\0';
    }
}

void Create(String *S){
    printf("please enter the string:\n");
    char ch='\0';
    S->length = 0;
    while (true){
        scanf("%c",&ch);
        if (ch == '\n')
            break;
        S->str[S->length] = ch;
        S->length++;
    }

}

void Print(String S){
    for (int i = 0; i < S.length; ++i) {
        printf("%c",S.str[i]);
    }
    printf("\n");
}

bool BF(const char s[],const char p[] ,int s_length,int p_length){
    int i = 0, j = 0;
    while (i<s_length && j<p_length){
        if(s[i] == p[j]){
            ++i;
            ++j;
        } else{
            i = i-j+1;
            j= 0;
        }
    }
    if(j>=p_length)
        return true;
    else
        return false;

}

void KMP(char s[], char p[], int s_length, int p_length){
    int ne[p_length];
    ne[0] = -1;
    for (int i = 1, j = -1; i < p_length; ++i) {
        while (j>=0 && p[j+1] != p[i])
            j = ne[j];
        if(p[j+1] == p[i])
            j++;
        ne[i] = j;
    }

    for (int i = 0, j = -1; i < s_length; ++i) {
        while (j != -1 && s[i] != p[j+1])
            j = ne[j];
        if(s[i] == p[j+1])
            j++;
        if(j == p_length - 1){
            printf("%d ", i - j);
            j = ne[j];
        }
    }
}


int main(){
//    String S;
//
//    Create(&S);
//    printf("%d\n",S.length);
    char str1[20]="ababacabcccdddac";
    int str_1 = 16;
    int str_2 = 2;
    char str2[20]= "ac";

//    bool flag = BF(str1,str2,str_1,str_2);
//    if(flag)
//        printf("yes");
//    else
//        printf("No");
    KMP(str1,str2,str_1,str_2);
    return 0;
}


/*
int main() {
    cin >> n >> (p + 1) >> m >> (s + 1);
    for (int i = 2, j = 0; i <= n; i++) {
        while (j != 0 && p[i] != p[j + 1])
            j = ne[j];
        if (p[i] == p[j + 1])
            j++;
        ne[i] = j;
    }
    for (int i = 1, j = 0; i <= m; i++) {
        while (j && s[i] != p[j + 1])
            j = ne[j];
        if (s[i] == p[j + 1])
            j++;
        if (j == n) {
            printf("%d", i - n);
            j = ne[j];
        }
    }
    return 0;
}
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值