一、题目(来源:点击打开链接)
述 | |
---|---|
知识点 | 字符串,查找 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入两个字符串 |
输出 | 输出一个整数 |
样例输入 | asdfas werasdfaswer |
样例输出 | 6 |
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <string>
#include <string.h>
using namespace std;
//KMP方法中的next表
void getNext(string needle,vector<int> &next)
{
next[0]=-1;
int i=0,k=-1,size=needle.size();
while(i<size-1)
{
if(k==-1 || needle[i]==needle[k])
{
if(needle[++i]==needle[++k])
next[i]=next[k];
else
next[i]=k;
}
else
{
k=next[k];
}
}
}
//求最大公共字符长度
int strStr(string haystack, string needle) {
if(haystack.empty()||needle.empty())
return 0;
//将大小写统一转为小写
transform(haystack.begin(),haystack.end(),haystack.begin(),tolower);
transform(needle.begin(),needle.end(),needle.begin(),tolower);
int i=0,j=0,hSize=haystack.size(),nSize=needle.size(),max=0;
vector<int> next(nSize,0);
//获取next表
getNext(needle,next);
//求最大公共字符串长度
while(i<hSize&&j<nSize)
{
if(j==-1||haystack[i]==needle[j])
{
++i,++j;
max=max<j?j:max;//将每次求出的计算结果的最大值保存在max中
}
else
j=next[j];
}
return max;
}
//获取两个字符串的最大长度
int getCommonStrLength(char * pFirstStr, char * pSecondStr)
{
string haystack(pFirstStr),needle(pSecondStr);
//若为空,则返回
if(haystack.empty()||needle.empty())
return 0;
int i,size=needle.size(),max=0,tmp;
string str;
for(i=0;i<size;i++)
{
//避免从中间开始匹配麻烦,保证字符匹配是从头开始匹配的
str=needle.substr(i);
tmp=strStr(haystack,str);
max=max<tmp?tmp:max;
}
return max;
}
int main()
{
char haystack[1024], needle[1024];
cin>>haystack;
cin>>needle;
cout<<getCommonStrLength(haystack,needle)<<endl;
system("pause");
return 0;
}