判断一个字符串是否由另一个字符串旋转而成

if s1 = "stackoverflow" then the following are some of its rotated versions:

"tackoverflows"

"ackoverflowst"
"overflowstack"

where as "stackoverflwo" is not a rotated version.

 

通常的做法
algorithm checkRotation
( string s1 , string s2 )
 
if ( len ( s1 ) != len ( s2 ))
   
return false
 
if ( substring ( s2 , concat ( s1 , s1 ))
   
return true
 
return false
end



一个基于KMP的解决方案
bool is_rotation ( const string & str1 , const string & str2 )
{
 
if ( str1 . size ()!= str2 . size ())
   
return false ;

  vector
<size_t> prefixes ( str1 . size (), 0 );
 
for ( size_t i = 1 , j = 0 ; i < str1 . size (); i ++) {
   
while ( j > 0 && str1 [ i ]!= str1 [ j ])
      j
= prefixes [ j - 1 ];
   
if ( str1 [ i ]== str1 [ j ]) j ++;
    prefixes
[ i ]= j ;
 
}

  size_t i
= 0 , j = 0 ;
 
for (; i < str2 . size (); i ++) {
   
while ( j > 0 && str2 [ i ]!= str1 [ j ])
      j
= prefixes [ j - 1 ];
   
if ( str2 [ i ]== str1 [ j ]) j ++;
 
}
 
for ( i = 0 ; i < str2 . size (); i ++) {
   
if ( j >= str1 . size ()) return true ;
   
while ( j > 0 && str2 [ i ]!= str1 [ j ])
      j
= prefixes [ j - 1 ];
   
if ( str2 [ i ]== str1 [ j ]) j ++;
 
}

 
return false ;
}


c版本
int is_rotation ( char * s1 , char * s2 )
{
 
char * tmp1 ;
 
char * tmp2 ;
 
char * ref2 ;

 
assert ( s1 && s2 );
 
if (( s1 == s2 ) || ( strcmp ( s1 , s2 ) == 0 ))
   
return ( 1 );
 
if ( strlen ( s1 ) != strlen ( s2 ))
   
return ( 0 );

 
while (* s2 )
   
{
      tmp1
= s1 ;
     
if (( ref2 = strchr ( s2 , * s1 )) == NULL )
       
return ( 0 );
      tmp2
= ref2 ;
     
while (* tmp1 && (* tmp1 == * tmp2 ))
       
{
         
++ tmp1 ;
         
++ tmp2 ;
         
if (* tmp2 == '/0' )
            tmp2
= s2 ;
       
}
     
if (* tmp1 == '/0' )
       
return ( 1 );
     
else
       
++ s2 ;
   
}
 
return ( 0 );
}

posted @ 2011-04-24 23:48  BiG5  阅读(251)  评论(0编辑  收藏  举报