您的位置:首页 > 其它

求两个字符串最大的公共字串的长度

2013-11-26 22:36 253 查看
//2013-11-26 22:10

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

//转化成小写
void mytolower(char* strSrc)
{
	while ( *strSrc != '\0')
	{
		if ( *strSrc >= 'A' && *strSrc <= 'Z')
		{
			*strSrc = *strSrc +32;
		}
		strSrc ++;
	}
}

//
int GetCurCommonStrLength(char* strFirst,char* strSecond)
{
	int nLength = 0;
	while ( *strFirst == *strSecond)
	{
		nLength++;
		strFirst ++;
		strSecond++;
	}
	return nLength;
}

//求两个字符串的最大公共字符串的长度,不考虑字符串是否大小写
//比如“abcdefghijk”和“bcaabcdedd”返回5
int GetCommonStrLength(char* pStrFirst,char* pStrSecond)
{
	if ( NULL == pStrFirst || NULL == pStrSecond)
	{
		return 0;
	}

	if ( pStrFirst == "" || pStrSecond == "")
	{
		return 0;
	}

	char strFirsttemp[512] = {0};
	char strSecondtemp[512] = {0};

	strcpy(strFirsttemp,pStrFirst);
	strcpy(strSecondtemp,pStrSecond);

	mytolower(strFirsttemp);
	mytolower(strSecondtemp);

	char* strFirst = strFirsttemp;
	char* strSecond = strSecondtemp;

	int nCommonLength = 0;
	while ( *strFirst != '\0')
	{
		while ( *strSecond != '\0')
		{
			if ( *strFirst == *strSecond)
			{
				int nTempCommon = GetCurCommonStrLength(strFirst,strSecond);
				if ( nTempCommon > nCommonLength)
				{
					nCommonLength = nTempCommon;
				}
			}
			strSecond++;
		}
		strSecond = strSecondtemp;
		strFirst++;
	}
	return nCommonLength;
}

int main()
{
	char* str1 = "abcdefghijk";
	char* str2= "bcaabcdedd";

	char* str3 = "xxp520jh";
	char* str4 = "jh520xp";
	int n = GetCommonStrLength(str3,str4);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: