题目链接<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1005>
实验三 KMP算法
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1479 | Accepted: 756 |
Description
给定一个源串s和n个子串stri。判断stri是否是s的子串。
Input
输入数据有多组,对于每组测试数据 第一行源串S(S长度小于100000),第二行一个整数n, 表示下面有n个查询,每行一个字符串str。
Output
若str是S的子串,输出 yes 否则输出 no
Sample Input
acmicpczjnuduzongfei3icpcduliu
Sample Output
yesyesno
Hint
因为串的长度比较长,超过256,因此本题的串不适合用定长顺序存储表示来存储串,SString的长度放在第一个元素,这个元素占一个字节,最大255.
#include <iostream> #include <stdio.h> #include <map> #include <queue> #include <string.h> #include <string> #include <stack> #include <cmath> #include <algorithm> using namespace std; typedef long long LL; void getNex(char *p,int *next){ int i=0,j=-1,lp=strlen(p); next[0]=-1; while(i<lp-1){ if(j==-1||p[i]==p[j]) i++,j++,next[i]=j; else j=next[j]; } } int kmp(char *s,char *p){ int nex[100005]; int i=0,j=0; getNex(p,nex); int ls=strlen(s),lp=strlen(p); while(i<ls){ if(j==-1||s[i]==p[j]) i++,j++; else j=nex[j]; if(j>=lp) return i-lp; } return -1; } int main(){ char s[100005],p[100005]; int t; scanf("%s%d",s,&t); while(t--){ scanf("%s",p); int ans=kmp(s,p); if(ans>=0) printf("yes\n"); else printf("no\n"); } }