Problem Description
String matching is a common type of problem in computer science. One string matching problem is as following:
Given a string s[0…len−1], please calculate the length of the longest common prefix of s[i…len−1] and s[0…len−1] for each i>0.
I believe everyone can do it by brute force.
The pseudo code of the brute force approach is as the following:
We are wondering, for any given string, what is the number of compare operations invoked if we use the above algorithm. Please tell us the answer before we attempt to run this algorithm.
Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains one string in a line consisting of printable ASCII characters except space.
* 1≤T≤30
* string length ≤106 for every string
Output
For each test, print an integer in one line indicating the number of compare operations invoked if we run the algorithm in the statement against the input string.
Sample Input
3
_Happy_New_Year_
ywwyww
zjczzzjczjczzzjc
Sample Output
17
7
32
题解:套用扩展KMP板子,输出数组的和,详情见代码
AC代码:
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstring>
#define ll long long
using namespace std;
const int maxn=1e6+5;
int ext[maxn],ex[maxn];
void GETNEXT(char *str)
{
int i=0,j,po,len=strlen(str);
ext[0]=len;//初始化next[0]
while(str[i]==str[i+1]&&i+1<len)//计算next[1]
i++;
ext[1]=i;
po=1;//初始化po的位置
for(i=2;i<len;i++)
{
if(ext[i-po]+i<ext[po]+po)//第一种情况,可以直接得到next[i]的值
ext[i]=ext[i-po];
else//第二种情况,要继续匹配才能得到next[i]的值
{
j=ext[po]+po-i;
if(j<0)j=0;//如果i>po+next[po],则要从头开始匹配
while(i+j<len&&str[j]==str[j+i])//计算next[i]
j++;
ext[i]=j;
po=i;//更新po的位置
}
}
}
//计算extend数组
void EXKMP(char *s1,char *s2)
{
int i=0,j,po,len=strlen(s1),l2=strlen(s2);
GETNEXT(s2);//计算子串的next数组
while(s1[i]==s2[i]&&i<l2&&i<len)//计算ex[0]
i++;
ex[0]=i;
po=0;//初始化po的位置
for(i=1;i<len;i++)
{
if(ext[i-po]+i<ex[po]+po)//第一种情况,直接可以得到ex[i]的值
ex[i]=ext[i-po];
else//第二种情况,要继续匹配才能得到ex[i]的值
{
j=ex[po]+po-i;
if(j<0)j=0;//如果i>ex[po]+po则要从头开始匹配
while(i+j<len&&j<l2&&s1[j+i]==s2[j])//计算ex[i]
j++;
ex[i]=j;
po=i;//更新po的位置
}
}
}
int main()
{
char s[maxn];
int T;
scanf("%d",&T);
while(T--)
{
ll ans=0;
scanf("%s",&s);
EXKMP(s,s);
for(int i=1;i<strlen(s);i++)
{
ans+=ex[i];
if(ex[i]+i!=strlen(s))
ans++;
}
printf("%lld\n",ans);
}
return 0;
}