给出一个字符串暴力的去求每个字符串的以不同的起点的每微的最长公共前缀和的算法,让你算一共进行了多少次的比较
思路:扩展kmp,扩展kmp用于求两个字符串的最长公共子序列(一个为主串,一个为模式串,主串的开头依次的后移),那么我们只要在每次的扩展kmp比较时判断是否已经比较到了最后一位,若没有则ans++
#include <stdio.h>
#include<string.h>
#define maxn 1000001
typedef long long ll;
using namespace std;
char str[maxn];
ll nex[maxn],extend[maxn];
ll GetNext(char *str)
{
ll ans=0;
int len=strlen(str),po,i;
nex[0]=len;
i=0;
while(str[i]==str[i+1]&&i+1<len)i++;//求出以1为开头的解
nex[1]=i;
ans+=i;
if(i+1!=len)ans++;
po=1;//用于标记最长的nex的下标
for(i=2;i<=len;i++)
{
if(nex[i-po]+i<nex[po]+po)//nex[i-po]等于len,len+i为总长度,nex[po]为最长的长度,nex[po]+po为最长长度
{
nex[i]=nex[i-po];
}
else
{
int j=nex[po]+po-i;//指向模式串的匹配位置
if(j<0)j=0;
while(str[j]==str[j+i]&&j+i<len)j++;
po=i;
nex[i]=j;
}
ans+=nex[i];
if(nex[i]+i!=len)
ans++;
}
return ans;
}
int main(int argc, char *argv[])
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",str);
printf("%lld\n",GetNext(str));
}
return 0;
}