FZU 1481 KMP

Source: Internet
Author: User

[Topic]

Determine whether the two ring strings are the same.

[Idea]

Copy the matching string to the end and use the pattern string as KMP. If it can be found, it indicates the same string.

I haven't written KMP for a long time, and I forgot about the algorithm ..

Little tragedy ~

[CODE]

#include<iostream>#include<cstdio>using namespace std;char t[222],s[444];int next[222];void setNext(){  next[0]=-1;  int j=0,k=-1;  while( j<strlen(t) )  {  if( k==-1||t[j]==t[k] )  next[++j]=++k;  else k=next[k]; }}bool judge(){  int l1=strlen(s),l2=strlen(t);  int i=0,j=0,k;  while( i<l1&&j<l2 )  {  if( j==-1||s[i]==t[j] )  i++,j++;  else  j=next[j]; } return j==l2;}int main(){ while( scanf("%s",&t)!=EOF ) {    setNext();    int sum=0,n;    scanf( "%d",&n );    while( n-- )    {     memset( s,0,sizeof(s) );     scanf( "%s",&s );     if( strlen(t)!=strlen(s) )       continue;     int len=strlen(s);     for( int i=0;i<len;i++ )        s[len+i]=s[i];       s[len<<1]=0;     if( judge() )       sum++;     }     printf( "%d\n",sum );  }  return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.