实验三 KMP算法

题目链接<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;
int nex[100005];
void getNex(char *p){
    int i=0,j=-1,lp=strlen(p);
    nex[0]=-1;
    while(i<lp){
        if(j==-1||p[i]==p[j]) i++,j++,nex[i]=j;
        else j=nex[j];
    }
}
int kmp(char *s,char *p){
    int i=0,j=0;
    getNex(p);
    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");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值