题目:
It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.
To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?
Input
The integer N in the first line denotes the total number of songs in the festival. Each of the following N lines consists of one string, indicating the notes of the i-th (1 <= i <= N) song. The length of the string will not exceed 10^6.
Output
There will be N lines in the output, where the i-th line denotes the maximum possible length of the theme section of the i-th song.
Sample Input
5
xy
abc
aaa
aaaaba
aaxoaaaaa
Sample Output
0
0
1
1
2
题意描述:
题目很有意思,输入一个字符串
计算并输出该串中“主题章节”的长度
解题思路:
属于KMP的next[]数组的应用。数据很水,放心提交。
代码实现:
/*
判断一个字符是否满足EAEBE,其中E为相同,满足输出最大的E的长度
找到EAEBE的相似度t=next[l],在找AEB中是否存在一个相似度为t,如果存在且t不等于0输出t,否则存在特殊情况
比如a
aa
aaa
结果均是l/3
*/
#include<stdio.h>
#include<string.h>
char s[];
int next[],l;
int get_next(char t[]);
int main()
{
int n,t,flag,i;
scanf("%d",&n);
while(n--)
{
scanf("%s",s);
l=strlen(s);
get_next(s);
t=next[l];
for(flag=,i=t;i<=l-t;i++)
{
if(next[i]==t)
flag=;
}
if(!flag || !t)
{
if(t+==l)
printf("%d\n",l/);
else
printf("0\n");
}
else
printf("%d\n",t);
}
return ;
}
int get_next(char t[])
{
int i,j;
i=;j=-;
next[]=-;
while(i < l)
{
if(j==- || t[i]==t[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
/*for(i=0;i<=l;i++)
printf("%d ",next[i]);
printf("\n");*/
}