您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之串一:KMP简单应用

2017-08-04 09:09 309 查看


数据结构实验之串一:KMP简单应用

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic


Problem Description

给定两个字符串string1和string2,判断string2是否为string1的子串。


Input

 输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。


Output

 对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。


Example Input

abc
a
123456
45
abc
ddd



Example Output

1
4
-1



Hint

 


Author

cjx

//和学密码那道题基本一模一样,水!

#include<bits/stdc++.h>

using namespace std;
char str1[1001000];
char str2[1001000];
int next[1001010];

void Get_Next()
{
memset(next,0,sizeof(next));
int len = strlen(str2);
next[0] = -1;
int k = -1;
int j = 0;
while(j < len)
{
if(k == -1 || str2[k] == str2[j])
{
j++;
k++;
next[j] = k;
}
else
k = next[k];
}
}

void KMP()
{
Get_Next();
int len = strlen(str1);
int lem = strlen(str2);
int i = 0; int j = 0;
while(i < len && j < lem)
{
if(j == -1 || str1[i] == str2[j])
{
i++;
j++;
}
else
j = next[j];
}
if(j >= lem)
cout<<i-lem+1<<endl;
else
cout<<"-1"<<endl;
}

int main()
{
while(cin>>str1>>str2)
{
KMP();
}
return 0;
}


4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 KMP 算法