求两个字符串的最大公共字串
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; }
相关文章推荐
- 求两个字符串最大的公共字串的长度
- 求两个字符串的最大公共字串问题
- 求两个字符串的最大公共字串
- 求两个字符串最大的公共字串的长度
- 华为机试:计算两个字符串的最大公共字串的长度,字符不区分大小写
- 计算两个字符串的最大公共字串的长度,字符不区分大小写(要求计算连续最长字串的长度)
- Exe 求两个字符串的最大公共字串
- 求两个字符串的最大连续公共字串
- 题目标题: 计算两个字符串的最大公共字串的长度,字符不区分大小写
- 两个字符串中最大的公共字串
- java 温习之字符串(获取两个字符串的最大公共字串)
- Java语言实现查找两个字符串的最大公共字串
- 求两个字符串的最大连续公共字串
- 求两个字符串的最大公共字串
- 两个或N个字符串最大公共子串算法
- 求两个字符串的最长公共字串(连续)
- 求两个字符串的最大公共子串
- 找出两个字符串中最大的公共子串的简单实现
- 求两个字符串的最大公共子串
- 获取两个字符串中最大的公共子串