一对一匹配,KMP算法

from:https://www.cnblogs.com/yjiyjige/p/3263858.html

模板:

#include<iostream>
#include<string>
#include<cstring>

using namespace std;
const int N = 1e5;     //字符串最大长度
string s, t;             //s主串,t模式串
int Next[N];         //不匹配时需要移动的位置

void findNext() {
    int k = -1;
    int i = 0;
    memset(Next, -1, sizeof Next);
    while (i < t.length() - 1) {
        if (k == -1 || t[i] == t[k]) {       //有重复的字符时
            if (t[++i] == t[++k])      // 当两个字符相等时要跳过
                Next[i] = Next[k];
            else
                Next[i] = k;
        } else
            k = Next[k];
    }
}

int KMP() {
    int i = 0, j = 0;
    while (i != s.length() && j != t.length()) {
        if (j == -1 || s[i] == t[j]) {  //当j为-1时,要移动的是i,当然j也要归0
            i++;
            j++;
        } else
            j = Next[j];          //j回到指定位置
    }
    if (j == t.length())         //找到匹配的
        return i - j;
    else
        return -1;
}

int main() {
    cin >> s >> t;
    findNext();
    int tPos = KMP();
    if (tPos == -1)
        cout << "Not has t!" << endl;
    else
        cout << "t is in " << tPos << "!" << endl;
    return 0;
}

/*
Input:
bacbababadababacambabacaddababacasdsd
ababaca
Output:
t is in 10!
*/
全部评论
太强了吧
点赞 回复 分享
发布于 2020-01-31 10:52

相关推荐

01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务