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

本文介绍了一种通过KMP算法来解决寻找字符串中最长重复子串的问题。文章详细阐述了如何利用KMP算法进行子串匹配的过程,并给出了完整的C++实现代码。读者将学会如何通过枚举子串并使用KMP算法高效地找出至少出现两次的最长子串。

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值