Experiment 3 KMP Algorithm

Topic link<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1005>

Experiment 3 KMP Algorithm
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 1479   Accepted: 756

Description

Given a source string s and n substrings stri. Check whether stri is a substring of s.

Input

There are multiple sets of input data. For each set of test data, the first line of the test data is a source string S (the length of S is less than 100000), and the second line contains an integer n, indicating that there are n queries below, and each line has a string str.

Output

If str is a substring of S, output yes, otherwise output no

Sample Input

acmicpczjnuduzongfei3icpcduliu

Sample Output

yesyesno

Hint

Because the length of the string is relatively long, exceeding 256, the string in this question is not suitable for storing the string in a fixed-length order. The length of the SString is placed in the first element, which occupies one byte, with a maximum of 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");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324783261&siteId=291194637