PTA: jmu-ds-实现KMP

给两个字符串A、B, 从A中找出第一次出现B的位置。

输入格式:

第一行输入一个整数n,表示测试数据的个数

对于每组测试数据,输入两个字符串S T,S和T中间用一个空格隔开,每组数据占一行。

输出格式:

对于每组测试数据,输出A中找出第一次出现B的位置,如果A不包含B,输出“not find!”

输入样例:

3
abcdabbcd abbc
abcd efg
abbcdd bbc

输出样例:

4
not find!
1

代码如下:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

void getNext(const string& pattern,vector<int>& next)
{
    int j=-1;
    next[0]=j;
    for(int i=1;i<pattern.size();i++)
    {
        while(j>=0&&pattern[i]!=pattern[j+1])
        {
            j=next[j];
        }
        if(pattern[i]==pattern[j+1])
        {
            j++;
        }
        next[i]=j;
    }
}

int kmp(const string& text,const string& pattern)
{
    vector<int> next(pattern.size());
    getNext(pattern, next);
    int j =-1;
    for(int i=0;i<text.size();i++)
    {
        while(j>=0&&text[i]!=pattern[j+1])
        {
            j=next[j];
        }
        if(text[i]==pattern[j+1])
        {
            j++;
        }
        if(j==(int)pattern.size()-1)
        {
            return i-pattern.size()+1;
        }
    }
    return -1;
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string text,pattern;
        cin>>text>>pattern;
        int pos=kmp(text,pattern);
        if(pos!=-1)
        {
            cout<<pos<<endl;
        }else{
            cout<<"not find!"<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值