编程练习——公共字串计算

描述

计算两个字符串的最大公共字串的长度,字符不区分大小写。

  • 时间限制:C/C++ 1秒,其他语言 2秒
  • 空间限制:C/C++ 32768K,其他语言 65536K

接口说明

原型:

int getCommonStrLength(char* pFirstStr, char* pSecondStr);

输入参数:

  • pFirstStr:第一个字符串
  • pSecondStr:第二个字符串

C代码实现

#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <time.h>

#define DEBUG 0

int getCommonStrLength(char* pFirstStr, char* pSecondStr)
{
	assert(pFirstStr && pSecondStr);

	int i, j, k, max=0;

    /* 将两个字符串转换为小写 */
	for(i=0; pFirstStr[i] != '\0'; i++) {
		pFirstStr[i] = tolower(pFirstStr[i]);
	}
	for(i=0; pSecondStr[i] != '\0'; i++) {
		pSecondStr[i] = tolower(pSecondStr[i]);
	}
#if(DEBUG)
	printf("getCommonStrLength(%s, %s)\n", pFirstStr, pSecondStr);
#endif
	for(i=0; pFirstStr[i] != '\0'; i++) {
		for(j=0; pSecondStr[j] != '\0'; j++) {
			if(pFirstStr[i] == pSecondStr[j]) {
				for(k=1; pFirstStr[i+k] != '\0' && pSecondStr[j+k] != '\0'; k++) {
					if(pFirstStr[i+k] != pSecondStr[j+k]) break;
				}
				if(k > max) max = k;
#if(DEBUG)
				printf("match: %c, i=%d, j=%d, len=%d, max=%d\n", 
                       pFirstStr[i], i, j, k, max);
#endif
			}
		}
	}
	return max;
}

int main(void)
{
	char firstStr[128] = {0};   /* 存放第一个字符串 */
	char secondStr[128] = {0};  /* 存放第二个字符串 */
	int  length = 0;
	clock_t begin, end;
	unsigned int run_time;

	scanf("%s %s", firstStr, secondStr);

	begin = clock();
	length = getCommonStrLength(firstStr, secondStr);
	end = clock();

	/* 统计算法执行时间 */
	run_time = (end - begin) * 1000.0 / CLOCKS_PER_SEC * 1000;

	printf("max=%d, time=%uus\n", length, run_time);
	
	return 0;
}

编译并执行代码,如下:

在这里插入图片描述

第一次测试启动了 DEBUG 打印匹配信息,第二次测试关闭了 DEBUG,因此第二次的执行时间 3μs 远小于第一次的 36μs。

发布了299 篇原创文章 · 获赞 1219 · 访问量 159万+

猜你喜欢

转载自blog.csdn.net/luckydarcy/article/details/102518842