问题描述:给定一个字符串,寻找这个字符串的最长重复子串,如abcdeabc,其最长的重复子串为abc。
问题解决:给定一个字符串,其最长重复子串的极端情况就是字符串长度的一半,如abcabc。那么我们就截取一些假定最长子串,然后和剩余的字符串比较,看看有没有存在子串。示例代码如下:
public class RepeatString {
String reg,left;
public String find(String str){
//the longest repeat string is the half of the primary string
for(int len=str.length()/2;len>0;len--){
//split the primary string into some strings,then judge whether it is repeat
for(int i=0;i<str.length()/len;i++){
//obtain the longest string
reg=str.substring(0,len+1);
//the rest of string
left=str.substring(len+1);
//judge whether the rest string has the longest string
if(left.indexOf(reg)!=-1){
return reg;
}
}
}
return null;
}
public static void main(String[] args) throws Exception{
String str=new RepeatString().find("abcuwhgikgfabc");
System.out.println(str);
}
}