OpenJudge 实现KMP

来源:互联网 发布:mysql replace where 编辑:程序博客网 时间:2024/06/06 09:57

OpenJudge 实现KMP
总时间限制: 1000ms 内存限制: 65535kB
描述
给两个字符串A、B, 从A中找出第一次出现B的位置。

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

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

S,T的长度均不超过20000
输出
对于每组测试数据,输出A中找出第一次出现B的位置,如果A不包含B,输出-1
样例输入
3
AAAAbAA Ab
AAABBB BB
XXXXXX YY
样例输出
3
3
-1
提示
使用KMP快速匹配算法能解决本题。 

#include<iostream>#include<string.h>using namespace std;#define MaxSize 20001int getNext(int next[],char s[]);int getNext(int next[],char s[]){    int i;    int Length;    int t=0;    Length = strlen(s);    next[0]=0;    for(i = 1; i < Length; i++)    {        if(s[i] == s[t])        {            next[i] = t++;        }        else        {            next[i] = t = 0;        }    }    return 0;}int KMP(char t[],char s[]){    int i = 0,j = 0;    int Lt,Ls;    int next[MaxSize];    getNext(next,t);    Lt = strlen(t);    Ls = strlen(s);    while(i < Ls && j < Lt)    {        if(s[i] == t[j] )        {            j++;            i++;        }        else if(s[i] != t[j] && j == 0)            {                i++;            }            else            {                j = next[j];            }    }    return (j == Lt) ? i-Lt : -1;}int main(){    int n;    char t[MaxSize],s[MaxSize];    cin>>n;    while(n--)    {        cin>>s;        cin>>t;        cout<<KMP(t,s)<<endl;    }    return 0;}


 

0 0
原创粉丝点击