题解 | #最长重复子串#
最长重复子串
http://www.nowcoder.com/practice/4fe306a84f084c249e4afad5edf889cc
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param a string字符串 待计算字符串
* @return int整型
*方法二:采用双指针
*/
public int solve (String a) {
// write code here
char[] char0 = a.toCharArray();
int max = 0;//初始化最长重复子串
int length = a.length();//字符串长度
int mayMaxLength = length/2;//可能最长重复子串
for (int i = 1; i <= mayMaxLength; i++) {
int count = 0;//计数器
for (int j = 0; j + i < length; j++) {
if (char0[j] == char0[j + i]){
count++;
} else {
count = 0;//重置count,即可以排除非连续子串
}
if(count == i) {//如果找到最长重复子串,直接退出,进入下一次循环
break;
}
}
if (i == count) max = Math.max(max, i);//取最大值
}
return max * 2;
}
}

查看14道真题和解析