* 最长重复子串 * 例子:给定一个字符串 * "we are the same human. human." * 输出: * " human.",注:空格也要算。
public class MaxRepeatSubString {
//解题思路,竟然是重复的子串,那么从某个地方,比如i开始的N个字符,都等于从j开始的N个字符。而且i<=j-N,i和j都大于N,N是重复字符串长度
public static String maxRepat(String input) {
if(input == null || input.length() == 0){
return null;
}
int subStrLength = Integer.MIN_VALUE;//记录重复子串N的长度
int maxSubStrLength = Integer.MIN_VALUE;//记录最大重复子串N的长度
int firstPosition = 0;//最大子串的起始位置,默认是0,最开始肯定是最大
//比较暴力的解法,双循环,遍历(input.length() -1)次
for (int i = 1; i < input.length(); i++) {
//比较元素j,和元素j+i是否相等,更新长度
for (int j = 0; j < input.length()-i; j++) {
if(input.charAt(j) == input.charAt(j+i)){
subStrLength++;
}else {
subStrLength = 0;
}
//每次都需要更新起始位置和最大长度
if(subStrLength > maxSubStrLength){
maxSubStrLength = subStrLength;
firstPosition = j - subStrLength +1;
}
}
}
return input.substring(firstPosition,firstPosition+maxSubStrLength);
}
public static void main(String[] args) {
System.out.println(maxRepat("we are the same human. human."));
}
}