首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求C先人救急

2013-04-21 
求C前辈救急啊!!!有两个字符串A和B,比较两个字符串,输出连续最大长度的字串,比如abcdef和rraijdef输出def,

求C前辈救急啊!!!
有两个字符串A和B,比较两个字符串,输出连续最大长度的字串,比如abcdef和rraijdef输出def,怎么用个指针函数写啊??char* p1(char* p2,char * p3)    
[解决办法]


#include <cstring>
#include <iostream>
using namespace std;
void LCS(string str1,string str2)
{
int m=str1.length ();
int n=str2.length ();
int R[15][15]={0};        //用来记录匹配情况
int max=0;
int end=0;
for(int x=0;x<m; x++)
{
for(int y=0;y < n; y++)
{
if(str1[x]==str2[y])
{
if(x==0
[解决办法]
y==0)
{
R[x][y]=1;
}
else
{
R[x][y]=R[x-1][y-1]+1;
}
}
if(R[x][y]>max)
{
max=R[x][y];
end=y;
}
}  
}
int start=end-max+1;
for(int i=start;i<=end;i++)
{
cout<<str2[i];
}
}
int main()
{
string str1="abcdef";   //要比较的两个字符串
string str2="rraijdef";
LCS(str1,str2);
cout << endl;
system("pause");
}

仅供参考
[解决办法]
char * findMaxLength( char *p2,  char *p3)
{
    char *pS = NULL;        // 短串
    char *pL = NULL;        // 长串
    size_t n2 = strlen(p2);
    size_t n3 = strlen(p3);
    size_t n = 0;
    if ( n2 > n3)
    {
        pS = p3;
        pL = p2;
        n = n3;
    } 
    else
    {
        pS = p2;
        pL = p3;
        n = n2;
    }

    char *p = new char[n+1];        // 结果字符串
    p[n] = '\0';
    strncpy(p ,pS ,n);
    if (strstr(pL ,p))      // 先比较整个
    {
        printf("%s\n" ,p);
    }
    else
    {
        p[0] = '\0';  // 细节处理,防止没有匹配到后返回整个短字符串
        for (int i = n; i != 0 ;--i)
        {
            p[i] = '\0';
            for (int j = 0; j != n-i+1; ++j)
            {


                memcpy(p ,pS+j ,i);
                if (strstr(pL ,p))
                {
//                    printf("%s\n" ,p);      // 打印出来看看,调用者负责释放该空间
                    return p;
                }
            }
        }
    }
}



int main(int argc, _TCHAR* argv[])
{
    char str1[] = "sbcdefiads";
    char str2[] = "rrrrabcdefijdef";
    char *p = findMaxLength(str1 ,str2);
    printf("%s\n" ,p);
 
    return 0;

}

热点排行