您的位置:首页 > 编程语言 > C语言/C++

最大公共字串

2014-07-03 13:29 211 查看
写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码就是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!

计算两个字符串的最大公共子串,忽略字符串大小写,由于OJ编译器要求,这里变量全部定义在开头。

#include "stdafx.h"
#include<iostream>
#include <string.h>
using namespace std;

int getCommonStrLength(char * ppFirstStr, char * ppSecondStr)
{
int i = 0;
int j = 0;
int len = 0;
int maxlen = 0;
int p = 0;

if (ppFirstStr == NULL || ppSecondStr == NULL)
{
return 0;
}
char *pFirstStr = strlwr(ppFirstStr);
char *pSecondStr = strlwr(ppSecondStr);

while (pFirstStr[i] != '\0')
{
p = i;
while (pSecondStr[j] != '\0' && pSecondStr[j] != pFirstStr[p])
{
j++;
}
if (pSecondStr[j] == '\0')
{
j = 0;
i++;
}else{
while(pFirstStr[p] != '\0' && pSecondStr[j] != '\0' && pFirstStr[p] == pSecondStr[j])
{
len++;
p++;
j++;
}
if (maxlen < len)
{
maxlen = len;
}
j = 0;
i++;
len = 0;
}
}
return maxlen;
}

int _tmain(int argc, _TCHAR* argv[])
{
/*
char *pFirstStr = "asdfas";
char *pSecondStr = "werasdfaswer";
*/
char *pFirstStr = new char[256];
char *pSecondStr = new char[256];
cin>>pFirstStr>>pSecondStr;
cout<<getCommonStrLength(pFirstStr,pSecondStr);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++