hdu_3746_kmp_给你一个字符串要求你添加最少的字符串使字符串最少循环两次

来源:互联网 发布:淘宝收到货后申请退款 编辑:程序博客网 时间:2024/05/18 02:51

题意:
给你一个字符串要求你添加最少的字符串使字符串最少循环两次,
Sample Input
3
aaa
abca
abcde
Sample Output
0
2
5
解;
kmp_next求最小循环结,然后直接求最小添加就行

#include<bits/stdc++.h>using namespace std;const int N=(int) 1e5+10;int m,nxt[N];void getnext(char *s){    int i=0,j=-1;    nxt[0]=-1;    while(i<m)    {        if(j==-1||s[i]==s[j])            nxt[++i]=++j;        else j=nxt[j];    }}int main(){    char s[N];    int t,i,j;    while(cin>>t)    {        while(t--)        {            scanf("%s",s);            m=strlen(s);            getnext(s);            int len=m-nxt[m];            if(len!=m&&m%len==0)                puts("0");            else                cout<<len-m%len<<endl;        }    }    return 0;}
原创粉丝点击