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).
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 one number — length of the longest substring that can be met in the string at least twice.
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;
}
本文介绍了一种通过KMP算法来解决寻找字符串中最长重复子串的问题。文章详细阐述了如何利用KMP算法进行子串匹配的过程,并给出了完整的C++实现代码。读者将学会如何通过枚举子串并使用KMP算法高效地找出至少出现两次的最长子串。
864

被折叠的 条评论
为什么被折叠?



