您的位置:首页 > 其它

找公共子串

2015-09-02 12:31 183 查看
In asdff fffasdfffaaaf

Out 5

寻找公共子串,我的思想就是两层循环,,最短每层的一个i开始最大与长的字符串的共同子串,遍历,暴力搜索。

注意大小写, 和注意思路就好

只有280分,如果有优化代码,请多多指教:

代码如下,

#include <stdio.h>
#include <ctype.h>
#include <iostream>
using namespace std;
#include <string>

int main()
{
int getCommonStrLength(char * pFirstStr, char * pSecondStr);
char pFirstStr[128];
char pSecondStr[128];
cin>>pFirstStr;
cin>>pSecondStr;
int a=getCommonStrLength(pFirstStr,pSecondStr);
cout<<a<<endl;
system("Pause");
return 0;
}
void mytower(char* strSrc)
{
while(*strSrc!='\0')
{
if (*strSrc>='A'&&*strSrc<='Z')
{
*strSrc=*strSrc+32;
}
strSrc++;
}
}
int getCommonStrLengthPart(char *pSmall,char *strSecond)
{
int nCount=0;
while(*pSmall==*strSecond&&(*pSmall!='\0'&&strSecond!='\0'))
{
nCount++;
pSmall++;
strSecond++;
}
return nCount;
}
int getCommonStrLength(char * pFirstStr, char * pSecondStr)
{
int count=0;
int MaxCount=0;
mytower(pFirstStr);
mytower(pSecondStr);
int pNumber1=strlen(pFirstStr);
int pNumber2=strlen(pSecondStr);
if (pNumber1==0||pNumber2==0)
{
return 0;
}
char *pSmall;
char *plonger;
int SmallNumber,longLength;
pNumber1<=pNumber2? pSmall=pFirstStr:pSmall=pSecondStr;
pNumber1<=pNumber2? plonger=pSecondStr:plonger=pFirstStr;
pNumber1<=pNumber2? (SmallNumber=pNumber1,longLength=pNumber2):(SmallNumber=pNumber2,longLength=pNumber1);

//fen bian hou
for (int i=0;i<SmallNumber;i++)
{
for (int j=0;j<longLength;j++)
{
count=getCommonStrLengthPart(&pSmall[i],&plonger[j]);
{
if (count>MaxCount)
{
MaxCount=count;

}

}
}
}
return MaxCount;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: