zoukankan      html  css  js  c++  java
  • 求两个字符串的最大公共字串

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



  • 相关阅读:
    启动控制面板命令大全
    C#下载网页为mht文件
    基于C#语言的可编程表达式计算器设计
    FileSystemWatcher监视文件变动
    C#梁朝伟变刘德华之山寨实现
    Json之语法,格式
    Regex类
    C# 索引器
    优化正则表达式的诀窍
    正则表达式(二) 零宽断言与懒惰匹配以及平衡组
  • 原文地址:https://www.cnblogs.com/aukle/p/3221692.html
Copyright © 2011-2022 走看看