现在的位置: 首页 > 综合 > 正文

一道题_20121221【转载】

2017年12月11日 ⁄ 综合 ⁄ 共 671字 ⁄ 字号 评论关闭

开始写写博客,做做笔记,学习学习。

//符串A和B,输出A和B中的最大公共子串。
//比如A="aocdfe" B="pmcdfa" 则输出"cdf"

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

char * comstr(char shortstr[], char longstr[])
{
	int i, j;
	char * com = new char[255];
	
	if(strstr(longstr, shortstr) != NULL)   
		return shortstr;  

	for(i = strlen(shortstr)-1; i > 0; i--) 
	{
		for(j = 0; j <= strlen(shortstr) - i; j++)
		{
			memcpy(com, &shortstr[j], i);
			com[i] = '\0';
			if(strstr(longstr, com) != NULL)
			return com;
		}
	}
	return "NULL";
}

main()
{
	char * str1 = (char *)malloc(256);
	char * str2 = (char *)malloc(256);
	char * com = NULL;
	printf("输 入 字 符 串:");
	gets(str1);
	printf("再次输入字符串:");
	gets(str2);
	if(strlen(str1) > strlen(str2))
		com = comstr(str2, str1);
	else
		com = comstr(str1, str2);
	printf("二者间最长字符串是: %s\n", com);

	system("pause");
}

运行结果

【上篇】
【下篇】

抱歉!评论已关闭.