運用KMP的next數組求字符串的最大週期,時間複雜度O(n)

#include<iostream>
#include<string>
using namespace std;
void getNext(string&str,int *next)
{
    int i,j;
    next[i=0]=j=-1;
    while(i<static_cast<int>(str.size()))
    {
        if(j==-1||str[i]==str[j])
        {
            next[++i]=++j;
        }
        else
        {
            j =next[j] ;
        }
    }
}
int main()
{
    string str;
    getline(cin,str);
    int *next =new int[str.size()+1];
    getNext(str,next);
    int len=str.size();
    cout << len/(len-next[len]) << endl;
    return 0;
}
相關文章
相關標籤/搜索