读书人

20分钟不到写的求两个字符串最大公共字

发布时间: 2012-05-30 20:20:04 作者: rapoo

20分钟不到写的求两个字符串最大公共字串的小程序,欢迎大家指正不足之处。
假如我20分钟不到就写出来这样的程序,算什么样的水平呢?

C/C++ code
#include <stdio.h>#include <string.h>#include <malloc.h>#define INVALID_PARA -1#define FAIL 1#define SUCCESS 0#define NOT_FOUND 2typedef unsigned long ulong;ulong get_common_string(char* pStr1, char* pStr2, char** pResult);int main(){    char str1[] = "abcdefg";    char str2[] = "hbcdefgh";    char* pstr = (char*)malloc(10);    memset(pstr,0,10);    if (SUCCESS == get_common_string(str1, str2, &pstr))    {        printf(pstr);    }    free(pstr);    return 0;}ulong get_common_string(char* pStr1, char* pStr2, char** pResult){    ulong match_count_max = 0;    ulong match_count = 0;    ulong val = 0;    ulong pos = 0;    char* pcTemp1 = NULL;    char* pcTemp2 = NULL;    if ((NULL == pStr1) || (NULL == pStr2) || (NULL == pResult))    {        return INVALID_PARA;    }        pcTemp1 = pStr1;    pcTemp2 = pStr2;    while ('\0' != *pStr1)    {        while('\0' != *pStr2)        {            while((pStr1[val]==pStr2[val]) && ('\0' != pStr1[val]) && ('\0' != *pStr2))            {                match_count++;                val++;            }            if(match_count > match_count_max)            {                match_count_max = match_count;                pos = strlen(pcTemp1) - strlen(pStr1);            }                        pStr2++;        }        val = 0;        match_count = 0;        pStr1++;        pStr2 = pcTemp2;    }    if (0 == match_count_max)    {        return NOT_FOUND;    }    else    {        strncpy(*pResult, pcTemp1 + pos, match_count_max);        return SUCCESS;    }}


[解决办法]

不错 支持一下
提点小意见 毕竟人和人写代码的风格都不一样
最好在函数的开始都写点注释 介绍下函数功能
写的时候 感觉效率能提高一下
不知道LZ的复杂度是多少 最快应该是 较长串长度为m 较短串长度为n 求得m*n
LZ测试下自己的算法怎么样
[解决办法]
是不是排序后在找回快一些,这样如果是很长的一个回很慢。n平方
[解决办法]
哎。。。。。。。。。。。
[解决办法]
code 很不错,喜欢的风格
[解决办法]
while((pStr1[val]==pStr2[val]) && ('\0' != pStr1[val]) && ('\0' != *pStr2))
这句话是不是错了?
while((pStr1[val]==*pStr2)) && ('\0' != pStr1[val]) && ('\0' != *pStr2))
是不是应该这样?

读书人网 >C语言

热点推荐