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


    //今天面试遇到一个有趣的题目 取两个字符串的最大公共字符串
    //解决方案如下:
    
    #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;
    }



  • 相关阅读:
    linux----别名
    linux---三剑客
    如何給linux安装 jdk呢?
    linux---文件颜色含义
    reason: no instance(s) of type variable(s) exist so that ProjectByProvinceVO conforms to ProjectDetailVO
    jrebel的坑
    使用自定义注解,但是运行时获取不到注解的值
    springboot启动失败,没有任何提示,trycatch也没有输出
    case when 中计数如何去重
    case when 中如何使用计数
  • 原文地址:https://www.cnblogs.com/aukle/p/3221692.html
Copyright © 2020-2023  润新知