zoukankan      html  css  js  c++  java
  • 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;
    }


  • 相关阅读:
    匈牙利算法自主总结
    luogu P2071 座位安排
    luogu P1613 跑路
    luogu P1250 种树
    luogu P1744 采购特价商品
    网络流
    其他图论
    组合计数
    小技巧
    矩阵&&高斯消元
  • 原文地址:https://www.cnblogs.com/CKboss/p/3350955.html
Copyright © 2011-2022 走看看