请从字符串中找出至少重复一次的子字符串的最大长度
输入描述:
字符串,长度不超过1000
输出描述:
重复子串的长度,不存在输出0
示例1
输入
ababcdabcefsgg
输出
3
说明
abc为重复的最大子串,长度为3
#include <iostream>
#include <string>
using namespace std;
int statLen(string str, int i, int j) {
int cur_len = 0;
while (i < str.size() && j < str.size() && str[i] == str[j]) {// 判断子串
i++;
j++;
cur_len++;
}
return cur_len;
}
int naiveLRS(string str) {
int maxlen = 0;
// 遍历所有字符串
for (int i = 0; i != str.size(); ++i) {
int len = 0;
for (int j = i + 1; j != str.size(); j++) {
len = statLen(str, i, j);// 获取子串长度
if (maxlen < len) { // 记录最大长度
maxlen = len;
}
}
}
return maxlen;
}
int main() {
string str;
cin >> str;
printf("%d", naiveLRS(str));
}
import java.util.*
public class Main{
private static int statLen(String X,int k,int j){
int cur_len = 0;
while(k < X.length()&&j<X.length()&&X.charAt(k) == X.charAt(j)){
k++;
j++;
cur_len++;
}
return cur_len;
}
public static int nativeLRS(String x){
int maxlen = 0;
int length = x.length();
for(int i = 0; i < length; i++){
int len = 0;
int k = i;
for(int j = i+1;j<length;j++){
len = staLen(x,k,j);
if(maxlen < len)
maxlen = len;
}
}
return maxlen;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String X = sc.nextLine();
System.out,println(nativeLRS(X));
}
}