Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 670 Accepted Submission(s): 94
简单的kmp算法,由于Strstr要运算多次没有KMP灵活所以运用strstr有可能会超时。虽然本题不难,但是有一个地方需要注意。看了这组例子想必就该明白了
sdfg asdf asdfg
ghjk asdf asdfghjk
asdf ghj asdfghj
aghjks ghjk aghjksghjk
ghjk aghjks aghjksghjk
特别注意最后两组例子
代码:
#include < stdio.h >
#include < string .h >
int next[ 100005 ];
void getnext( char * t)
{
int i = 1 ,j = 0 ;next[ 1 ] = 0 ;
int len = strlen(t + 1 );
while (i < len)
{
if (j == 0 || t[i] == t[j])
{
++ i; ++ j;next[i] = j;
}
else
j = next[j];
}
}
int kmp( char * s, char * t)
{
int i,j,len1,len2;
getnext(t);
i = 1 ;j = 1 ;
len1 = strlen(s + 1 );len2 = strlen(t + 1 );
while (i <= len1 && j <= len2)
{
if (j == 0 || s[i] == t[j])
{
++ i; ++ j;
}
else
{
j = next[j];
}
}
if (j > len2 && i <= len1)
return 0 ;
return j - 1 ;
}
char str1[ 100005 ],str2[ 100005 ];
int main()
{
int mark1,mark2,j;
while (scanf( " %s%s " ,str1 + 1 ,str2 + 1 ) != EOF)
{
mark1 = kmp(str1,str2);
mark2 = kmp(str2,str1);
if (mark1 == mark2)
{
if (strcmp(str1 + 1 ,str2 + 1 ) >= 0 )
{
printf( " %s " ,str2 + 1 );
for (j = mark1 + 1 ;str1[j] != ' \0 ' ;j ++ )
printf( " %c " ,str1[j]);
}
else
{
printf( " %s " ,str1 + 1 );
for (j = mark2 + 1 ;str2[j] != ' \0 ' ;j ++ )
printf( " %c " ,str2[j]);
}
}
else if (mark1 > mark2)
{
printf( " %s " ,str1 + 1 );
for (j = mark1 + 1 ;str2[j] != ' \0 ' ;j ++ )
printf( " %c " ,str2[j]);
}
else if (mark2 > mark1)
{
printf( " %s " ,str2 + 1 );
for (j = mark2 + 1 ;str1[j] != ' \0 ' ;j ++ )
printf( " %c " ,str1[j]);
}
printf( " \n " );
}
return 0 ;
}