您的位置:首页 > 其它

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

2015-09-10 17:13 399 查看
求两个字符串最大的公共字串的长度

1、暴力解法

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

/*大写转化成小写*/
void large_to_little(char* strSrc)
{
    if(!strSrc)
        return;
    while ( *strSrc != '\0')
    {
        if ( *strSrc >= 'A' && *strSrc <= 'Z')
        {
            *strSrc = *strSrc +'a'-'A';
        }
        strSrc ++;
    }
}

/*获取当前字符串的长度*/
int getCurCommonStrLength(char* pFirstStr,char* pSecondStr)  
{  
    int nLength = 0;  
    if(!pFirstStr||!pSecondStr)
        return 0;
    while ((*pFirstStr == *pSecondStr)&&(*pFirstStr!='\0'||*pSecondStr!='\0')) {  
        nLength++;  
        pFirstStr ++;  
        pSecondStr++;  
    }  

    return nLength;  
}  

/*获取公共字符串的长度*/
int getCommonStrLength(char * pFirstStr, char * pSecondStr)
{
    if(!pFirstStr||!pSecondStr)
        return 0;
    if(pFirstStr==""||pSecondStr=="")
        return 0;

    /*1.大小写会改变原字符串,保留原字符串*/
    int pFirstStrLen = strlen(pFirstStr);
    int pSecondStrLen = strlen(pSecondStr);
    /*字符串结束标志位*/
    char *pFirstStrTemp = (char *)malloc(pFirstStrLen*sizeof(char)+1);
    char *pSecondStrTemp = (char *)malloc(pSecondStrLen*sizeof(char)+1);

    strcpy(pFirstStrTemp,pFirstStr);  
    strcpy(pSecondStrTemp,pSecondStr); 
    /*转换成小写*/
    large_to_little(pFirstStrTemp);  
    large_to_little(pSecondStrTemp);  
    /*2.获取公共字符串长度*/
    int CommonStrLengthMax = 0;

    char* strFirst = pFirstStrTemp;  
    char* strSecond = pSecondStrTemp; 
    //printf("[%d] strFirst %s\n",__LINE__,strFirst);
    //printf("[%d] strFirst %s\n",__LINE__,strSecond);

    while ( *strFirst != '\0') { 

        while ( *strSecond != '\0') { 

            if ( *strFirst == *strSecond) {  
                int nTempCommon = getCurCommonStrLength(strFirst,strSecond);  
                if ( nTempCommon > CommonStrLengthMax) {  
                    CommonStrLengthMax = nTempCommon;  
                    //printf("[%d] CommonStrLengthMax %d\n",__LINE__,CommonStrLengthMax);
                }  
            }  
            strSecond++;  
        }  
        strSecond = pSecondStrTemp;  /*重新赋值*/
        //printf("[%d] strFirst %s\n",__LINE__,strSecond);
        strFirst++;  
    }  

    free(pFirstStrTemp);
    free(pSecondStrTemp);

    return CommonStrLengthMax;

}

int main()
{
#if 0
    char* str1 = "asdfas";  
    char* str2= "werasdfaswer";  
#endif

#if 0
    char* str1 = "123456";  
    char* str2= "123564123456";  
#endif

#if 0 
    char str1[1024];
    char str2[1024];
    gets(str1);
    gets(str2);
#endif
/*1.输入字符串之间要有空格*/
#if 1 
    char str1[1024];
    char str2[1024];

    scanf("%s %s",str1,str2);
#endif
    //printf("%s\n",str1);
    int CommonStrLengthMax = getCommonStrLength(str1,str2); 
    printf("%d\n",CommonStrLengthMax);
#if 0
    getchar();
    getchar();
#endif
    return 0;
}


2、动态规划(待完善)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: