| 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.
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
|
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
using namespace std;
char x[1000001];
long long Next[1000001],ex[1000001];
void getNext(char *str)
{
int i=0,j,po,len=strlen(str);
Next[0]=len;
while(str[i]==str[i+1]&&i+1<len)
i++;
Next[1]=i;
po=1;
for(i=2;i<len;i++)
{
if(Next[i-po]+i<Next[po]+po)
Next[i]=Next[i-po];
else
{
j=Next[po]+po-i;
if(j<0)j=0;
while(i+j<len&&str[j]==str[j+i])
j++;
Next[i]=j;
po=i;
}
}
}
void getkmp(char *s1,char *s2)
{
int i=0,j,po,len=strlen(s1),l2=strlen(s2);
getNext(s2);
while(s1[i]==s2[i]&&i<l2&&i<len)
i++;
ex[0]=i;
po=0;
for(i=1; i<len; i++)
{
if(Next[i-po]+i<ex[po]+po)
ex[i]=Next[i-po];
else
{
j=ex[po]+po-i;
if(j<0)j=0;
while(i+j<len&&j<l2&&s1[j+i]==s2[j])
j++;
ex[i]=j;
po=i;
}
}
}
int main()
{
long long int i,t,n,s;
scanf("%lld\n",&t);
while(t--)
{
memset(ex,0,sizeof(ex));
s=0;
scanf("%s",x);
n=strlen(x);
getkmp(x,x);
for( i=1;i<=n-1;i++)
{
if(ex[i]==0)
s++;
else
s+=ex[i]+1;
if(ex[i]+i>=n)
s--;
}
printf("%lld\n",s);
}
}

本文深入探讨了计算机科学中常见的字符串匹配问题,特别是针对给定字符串计算每个子串与其自身最长公共前缀长度的问题。通过分析暴力算法的比较操作次数,提出了一种更高效的解决方案,并附带了详细的代码实现。

519

被折叠的 条评论
为什么被折叠?



