HDU

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
/*************************************************************************************************************
            求目标串中出现了多少个模式串
            1,ans++;
            2,j = 0;

*************************************************************************************************************/

int Next[1005];
string s,p;

void getNext(int m){
    int i = 0,j = -1;
    Next[0]=-1;

    while(i < m){
        while(j != -1 && p[i] != p[j])
            j = Next[j];
        if(p[++i] == p[++j])    Next[i] = Next[j];
        else
            Next[i]=j;
    }
}

int Kmp(int n,int m){
    getNext(m);
    int i = 0,j = 0;
    int ans = 0;
    while(i < n && j < m){
        while(j != -1 && s[i] != p[j])
            j = Next[j];
        i++;
        j++;
        if(j >= m){
            ans++;
            j = 0;
        }
    }
    return ans;
}

int main()
{
    while(cin>>s){
        if(s[0] == '#') break;
        cin>>p;
        int lt1=s.length(),lt2=p.length();
        cout<<Kmp(lt1,lt2)<<endl;
    }
    return 0;
}



原文地址:https://www.cnblogs.com/Jstyle-continue/p/6351966.html