您的位置:首页 > 其它

You're Given a String... (kmp)

2018-02-09 16:10 375 查看

You're Given a String...

You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Input The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.
Output Output one number — length of the longest substring that can be met in the string at least twice.
Example Input
abcd
Output
0
Input
ababa
Output
3
Input
zzz
Output
2
枚举子串,kmp匹配
code:#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int MAXN = 110;
string s;
string w;
int Next[MAXN];
void getNext(){
int i = -1,j = 0;
int len = s.length();
memset(Next,0,sizeof(Next));
Next[0] = -1;
while(j < len){
if(i == -1 || w[i] == w[j]){
i++,j++;
Next[j] = i;
}
else
i = Next[i];
}
}
int kmp(){
int i = 0, j = 0,cnt = 0;
int lens = s.length();
int lenw = w.length();
getNext();
while(j < lens){
if(i == -1 || w[i] == s[j])
i++,j++;
else
i = Next[i];
if(i == lenw)
cnt++;
}
return cnt;
}
int main(){
int i,j;
int ans = 0;
cin >> s;
for(i = 0; i < s.length(); i++){
for(j = i; j < s.length(); j++){
w = s.substr(i,j-i+1);
if(kmp() >= 2){
int len = j-i+1;
ans = max(ans,len);
}
}
}
cout << ans << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: