【数据结构】串的模式匹配(C语言实现)

文章提供了两种C语言实现的字符串匹配算法:普通算法和KMP算法。普通算法在匹配失败时会回溯;KMP算法通过预处理next数组优化了匹配过程,减少了不必要的回溯。两段代码分别实现了这两种算法,并在main函数中接收用户输入,找出模式串在目标串中的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5.2.1 普通算法

程序代码:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAXSIZE 100

int mate(char* P, char* T) {

    int i = 0, j = 0;

    while (i < strlen(P) && j < strlen(T)) {

        if (P[i] == T[j]) {

            i++;

            j++;

        }

        else {

            i = i - j + 1;

            j = 0;

        }

    }

    if (j == strlen(T)) {

        return i - strlen(T) + 1;

    }

    return -1;

}

int main() {

    char* P=(char*)malloc(sizeof(char)*MAXSIZE);

    char* T=(char*)malloc(sizeof(char)*MAXSIZE);

    printf("请输入目标T:\n");

    scanf("%s", T);

    printf("请输入模式P:\n");

    scanf("%s", P);

    int number = mate(T, P);

    printf("%d", number);

    return 0;

}

运行截图:

 

5.2.2 KMP算法

程序代码:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define MAXSIZE 100

void Next(char* T, int* next) {

    int i = 1;

    next[1] = 0;

    int j = 0;

    while (i < strlen(T)) {

        if (j == 0 || T[i - 1] == T[j - 1]) {

            i++;

            j++;

            next[i] = j;

        }

        else {

            j = next[j];

        }

    }

}

int KMP(char* S, char* T) {

    int next[10];

    Next(T, next);

    int i = 1;

    int j = 1;

    while (i <= strlen(S) && j <= strlen(T)) {

        if (j == 0 || S[i - 1] == T[j - 1]) {

            i++;

            j++;

        }

        else {

            j = next[j];

        }

    }

    if (j > strlen(T)) {

        return i - (int)strlen(T);

    }

    return -1;

}

int main() {

    char* P = (char*)malloc(sizeof(char) * MAXSIZE);

    char* T = (char*)malloc(sizeof(char) * MAXSIZE);

    printf("请输入目标T:\n");

    scanf("%s", T);

    printf("请输入模式P:\n");

    scanf("%s", P);

    printf("返回位置:");

    int i = KMP(T, P);

    printf("%d", i);

    return 0;

}

运行截图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃头鸭鸭鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值