您的位置:首页 > 其它

求两个字符串的最大公共字串

2013-07-26 15:51 351 查看
//今天面试遇到一个有趣的题目 取两个字符串的最大公共字符串
//解决方案如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//先造一个常用函数
char* strsub( char const* pStrSrc, int iStart, int iLen )
{
if( !pStrSrc || iStart <  0 )
return NULL;

int iStrLen = strlen( pStrSrc );

char* pStrRes = NULL;
if( iLen >= iStrLen - iStart )
{
pStrRes = (char*)malloc( iStrLen - iStart + 1 );

if( !pStrRes )
return NULL;

memset( pStrRes, 0,  iStrLen - iStart + 1 );

strncpy( pStrRes, pStrSrc + iStart, iStrLen  - iStart );

return pStrRes;
}
else
{
pStrRes = (char*)malloc( iLen + 1 );

if( !pStrRes )
return NULL;

memset( pStrRes, 0, iLen + 1 );

strncpy( pStrRes, pStrSrc + iStart, iLen );

return pStrRes;

}

}

char* maxComm( char* pStrLeft, char* pStrRight )
{
if( !pStrLeft || !pStrRight )
{
return NULL;
}

char* pStrLess = NULL;
char* pStrMore = NULL;
char* pStrRes= NULL;

int iLeft = strlen( pStrLeft );
int iRight = strlen( pStrRight );

int iLess = ( iLeft <= iRight ) ? iLeft : iRight;

int i,j;

if( iLeft <= iRight )
{
pStrLess = pStrLeft;
pStrMore = pStrRight;
}
else
{
pStrLess = pStrRight;
pStrMore = pStrLeft;
}
char* pSt = NULL;

for( i = iLess; i > 0; i-- )
{
for( j = 0; j <= iLess - i; j++ )
{
pStrRes = strsub( pStrLess, j, i );

if( strstr( pStrMore, pStrRes ) )
return pStrRes;

free( pStrRes );
pStrRes = NULL;
}
}

return NULL;
}

int main( int argc, char** argv )
{
char* pStrLeft = "adasdfabc";
char* pStrRight = "asdabcasdf";

puts( "max comm string between two strings" );
char* strMaxComm = maxComm( pStrLeft, pStrRight );
printf( strMaxComm );
puts( "" );

free( strMaxComm );
strMaxComm = NULL;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: