KMP

#include <string>
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

vector<int> kmp(string patten,string text)
{
    int n=patten.size();
    vector<int> next(n+1,0);
    for(int i=1;i<n;i++)
    {
        int j=i;
        while(j>0)
        {
            j=next[j];
            if(patten==patten[j])
            {
                next[i+1]=j+1;
                break; 
            }
        }
    }

    int m=text.size();
    vector<int> postion;

    for(int i=0,j=0;i<m;i++)
    {
        if(j<n&&text==patten[j])
        {
            j++;
        }
        else while(j>0)
        {
            j=next[j];
            if(text==patten[j])
            {
                j++;
                break;
            }
        }
        if(j==n)
        {
            postion.push_back(i-n+1);
        }
    }

    return postion;
}
int main()
{
    string text,partern;
    vector<int> vhd;
    while(cin>>text>>partern)
    {
        vhd=kmp(partern,text);

        for(int i=0;i<vhd.size();i++)
        {
            cout<<vhd<<" ";
        }
        cout<<endl<<endl;
    }

    return 0;
}


posted @ 2013-07-21 22:15  码代码的猿猿  阅读(160)  评论(0编辑  收藏  举报