KMP字符串模式匹配算法实现

给定字符串S和匹配串T,请你求出匹配串T在S中第一次正确匹配的索引位置。若匹配失败则返回0。
- 如题,C++版本的KMP代码模版如下:

样例输入
string str
thisisalongstring isa
nosubstring subt
样例输出
1
5
0

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

const int MAXN=102;
void get_next(char *T, int *next) {
    int i = 1;
    next[1] = 0;
    int j = 0;
    int Tlen=strlen(T+1);
    while (i < Tlen) {
        if (j == 0 || T[i] == T[j]) {
            ++i;
            ++j;
            next[i] = j;
        } else
            j = next[j];
    }
}
int Index_KMP(char *S, char *T, int pos) {
    // 利用模式串T的next函数求T在主串S中第pos个字符之后的位置的
    // KMP算法。其中,T非空,1≤pos≤StrLength(S)。
    int next[255];
    int i = pos;
    int j = 1;
    get_next(T, next);
    int Slen=strlen(S+1);
    int Tlen=strlen(T+1);
    while (i <= Slen && j <= Tlen) {
        if (j == 0 || S[i] == T[j]) { // 继续比较后继字符
            ++i;++j;
        }else j = next[j]; // 模式串向右移动
    }
    if (j > Tlen) return i - Tlen; // 匹配成功
    else return 0;
}
int main()
{
    char s[MAXN],t[MAXN];
    while(~scanf("%s%s",s+1,t+1)){
        printf("%d\n",Index_KMP(s,t,1));
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值