KMP算法(尝试)

本文介绍了一种使用KMP算法解决字符串匹配问题的方法,并通过一个具体的应用实例展示了如何实现字符串匹配及计数的功能。该程序能够高效地在主字符串中查找并统计模式字符串出现的次数。

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

//
//  main.c
//  test
//
//  Created by 胡博豪 on 16/2/29.
//  Copyright © 2016年 胡博豪. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int *next(const char *string) {
    int *next = (int *)malloc(sizeof(int) * 100);
    next[0] = next[1] = 0;
    int i = 0, j = 1;
    while (++j < strlen(string)) {
        if (string[i] != string[j]) {
            next[j] = 0;
            i = 0;
        } else {
            i++;
            next[j] = next[j - 1] + 1;
        }
    }
    return next;
}

int KMP(const char *ms, const char *os, const int *next) {
    int i, j = 0;
    for (i = 0; i < strlen(ms);) {
        if (ms[i] == os[j]) {
            j++;
            i++;
        } else {
            if (j == 0) {
                i++;
            }
            j = next[j];
        }
        if (j == strlen(os)) {
            return i - j + 1;
        }
    }
    return -1;
}

int count_str_in_str(char *str_m, const char *str_o) {
    int count = 0, temp = 0;
    int *n = next(str_o);
    char *str_temp = str_m;
    while (temp != -1) {
        temp = KMP(str_temp, str_o, n);
        str_temp += temp + 1;
        count++;
    }
    free(n);
    return count - 1;
}

int main(int argc, const char * argv[]) {
    int n, index;
    while(~scanf("%d", &n)) {
        char **sa = (char **)malloc(sizeof(char *) * n);
        for (index = 0; index < n; index++) {
            char *temp = (char *)malloc(sizeof(char) * 100);
            scanf("%s", temp);
            sa[index] = temp;
        }
        char data[100001];
        scanf("%s", data);
        char *re = NULL;
        int amount = 0;
        for (index = 0; index < n; index++) {
            int te = count_str_in_str(data, sa[index]);
            if (te > amount) {
                amount = te;
                re = sa[index];
            }
        }
        if (amount == 0) {
            printf("exciting\n");
        } else {
            printf("%s %d\n", re, amount);
        }
        for (index = 0; index < n; index++) {
            free(sa[index]);
        }
        free(sa);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

borehole打洞哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值