codevs 1204 寻找子串位置 KMP

1204:寻找子串位置

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 18K  Solved: 8K

Description

给出字符串a和字符串b,保证b是a的一个子串,请你输出b在a中第一次出现的位置。

Input

仅一行包含两个字符串a和b

字符串的长度均不超过100

Pascal用户请注意:两个字符串之间可能包含多个空格

Output

仅一行一个整数

Sample Input

abcd bc

Sample Output

2

HINT

题解:

这就是传说中的傻逼暴力题!

但是,我会传说中的KMP怎么破?

O(∩_∩)O哈哈哈~

代码:

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 100001
#define eps 1e-9
const int inf=0x7fffffff;   //无限大
void kmp_pre(char x[],int m,int next[])
{
    int i,j;
    j=next[0]=-1;
    i=0;
    while(i<m)
    {
        while(-1!=j&&x[i]!=x[j])j=next[j];
        next[++i]=++j;
    }
}
int next[maxn];
int Kmp_count(char x[],int m,char y[],int n)
{
    int i,j;
    int ans=0;
    //preKmp(x,m,next);
    kmp_pre(x,m,next);
    i=j=0;
    while(i<n)
    {
        while(-1!=j&&y[i]!=x[j])j=next[j];
        i++;j++;
        if(j>=m)
        {
            return i;
            ans++;
            j=next[j];
        }
    }
}
int main()
{

        char a[maxn];
        char b[1000001];
        scanf("%s%s",a,b);
        int n=strlen(a);
        int m=strlen(b);
        printf("%d
",Kmp_count(b,m,a,n)-m+1);
}
原文地址:https://www.cnblogs.com/qscqesze/p/4363600.html