求C前辈救急啊!!!

雏田控 2013-03-30 12:01:44
有两个字符串A和B,比较两个字符串,输出连续最大长度的字串,比如abcdef和rraijdef输出def,怎么用个指针函数写啊??char* p1(char* p2,char * p3)
...全文
95 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
_sunshine 2013-03-30
  • 打赏
  • 举报
回复

#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");
}
仅供参考
雏田控 2013-03-30
  • 打赏
  • 举报
回复
3q!!!csdn好人多啊~~ 用两个for循环搞出来了,感谢
starytx 2013-03-30
  • 打赏
  • 举报
回复
引用 3 楼 starytx 的回复:
C/C++ code ? 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 char * findMaxLength( char *p2, char *p3) { char *pS = NULL; ……
有个小bug,函数最后要加一句 return "";没有找到的话返回空串;26行换成 return p;开始做的时候只是想显示一下,忘记改成返回值了
starytx 2013-03-30
  • 打赏
  • 举报
回复
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;

}
starytx 2013-03-30
  • 打赏
  • 举报
回复
我的思路:先找出较短的那个(一样长的话就随便用一个),在这个短的上循环取段,在长的里边查找,循环的规则是,先取整个,不行就取第0个到长度-2个,再不行就第1个到长度-1个,再不行就第0个到长度-3个...以此类推

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧