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

转自:http://blog.sina.com.cn/s/blog_630622ba0100mrv3.html

求两个串中的第一个最长子串。

如"abractyeyt","dgdsaeactyey"的最大子串为"actyet"。


有一个算法很巧妙:
 

把字符串1(长度m)横排,串2(长度n)竖排,得到一个m×n的矩阵c,矩阵的每个元素的值如下,如果m[i]=n[j],则c[j][i]=1,否则,c[j][i]=0。然后找出矩阵中连续是1的对角线最长的一个,则对角线的长度就是公共子串的长度.

 

经过改进,可以不需要构造矩阵,因为第i行如果有字母匹配,其取值仅与第i-1行相关,若m[i]=n[j],则c[j][i] = c[j-1][i-1] + 1,这样仅需要记录一个长度为m的一维数组就可以了。

#include <stdio.h>
#include <stdlib.h>
char * StringSearch( char * str1, char * str2 )
{
    int i;
    int j;
    char* ptempBuffer1;
    char* ptempBuffer2;
    char* pwork;
    char* plast;
    char* ptemp;
    char* retstr;
    int resultIndex = 0;
    int resultLength = 0;
    int str1Size = 0;
    int str2Size = 0;
    ptempBuffer1 = str1;
    while( *ptempBuffer1 != '\0' )
    {
        ptempBuffer1++;
        str1Size++;
    }
    ptempBuffer2 = str2;
    while( *ptempBuffer2 != '\0' )
    {
        ptempBuffer2++;
        str2Size++;
    }
   
    ptempBuffer1 = ( char * ) malloc( str1Size );
    pwork = ptempBuffer1;
    memset( pwork, 0, str1Size );
    ptempBuffer2 = ( char * ) malloc( str1Size );
    plast = ptempBuffer2;
    memset( plast, 0, str1Size );
    for( i = 0; i < str2Size; i++ )
    {
        for( j = 0; j < str1Size; j++ )
        {
            if( *( str1 + j ) == *( str2 + i ) )
            {
                if( j == 0 )
                {
                    *( pwork + j ) = 1;
                }
                else
                {
                    *( pwork + j ) = *( plast + j - 1 ) + 1;
                }
                if( resultLength < *( pwork + j ) )
                {
                    resultIndex = j;
                    resultLength = *( pwork + j );
                }
            }
            else
            {
                *( pwork + j ) = 0;
            }
        }
        ptemp = pwork;
        pwork = plast;
        plast = ptemp;
    }
    retstr = ( char * ) malloc( resultLength + 1 );
    memcpy( retstr, str1 + resultIndex - resultLength + 1, resultLength );
    *( retstr + resultLength ) = '\0';
    printf( "resultIndex = %d, resultLength = %d\n", resultIndex, resultLength );
    free( ptempBuffer1 );
    free( ptempBuffer2 );
    return retstr;
}
int main(int argc, char *argv[])
{
    char* ret = NULL;
    ret = StringSearch( "adbccadebbca", "edabccadece" );
    printf( "result String is %s\n", ret );
    free( ret );
    system("PAUSE"); 
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值