HDOJ 2087 KMPアルゴリズム


// HDOJ 2087 KMP  
#include<iostream>
using namespace std;

#include<string>

void nextval(char s2[],int next[],int len)
{
        next[1] = 0;
        int i = 1,j = 0;
        while(i < len)
        {
                if(j == 0 || s2[i] == s2[j])
                {
                        ++i;
                        ++j;
                        if(s2[i] != s2[j]) next[i] = j;
                        else next[i] = next[j];
                }
                else j = next[j];
        }
}

int KMP(char s1[],char s2[],int len1,int len2,int next[],int pos)
{
        int i = pos,j = 1;
        while(i <= len1 && j <= len2)
        {
                if(j == 0 || s1[i] == s2[j])
                {
                        ++i;
                        ++j;
                }
                else j = next[j];
        }
        if(j > len2) return i;
        else return 0;
}

int main()
{
        string s1,s2;
        while(cin>>s1 && s1 != "#")
        {
                cin>>s2;
                int next[s2.size()+1],c = 0,pp = 0;
                next[0] = -1;
                char c1[s1.size()+1],c2[s2.size()+1];
                for(int i = 1;i <= s1.size();++i) c1[i] = s1[i-1];
                for(int i = 1;i <= s2.size();++i) c2[i] = s2[i-1];
                nextval(c2,next,s2.size());
                for(int pos = 1;pos <= s1.size();)
                {
                        pp = KMP(c1,c2,s1.size(),s2.size(),next,pos);
                        if(pp)
                        {
                                ++c;
                                pos = pp;
                        }
                        else break;
                }
                cout<<c<<endl;
        }

        return 0;
}