原理:一个字符串的重复子串的最长长度只能小于等于length/2; 所以从length/2开始递减循环,每次取出理论最长子串,在判断剩下的字符串里面有没有理论串,有就找到结果;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
String result=findMaxRepeat(str);
System.out.println(result);
}
public static String findMaxRepeat(String str){
int len=str.length();
String sample, left; //sample就是理论串, left就是剩下的字符串
for (int i = len/2; i>0; i--) {
for (int j = 0; j < len-i; j+=i) {
sample=str.substring(j,i);
left=str.substring(i);
if (left.indexOf(sample)!=-1) {
return sample;
}
}
}
return null;
}
}