输入一字符串,找出其中出现的相同且长度最长的子串,输出该子串的长度。规定字符串本身不能称为自己的子串。请编写效率尽可能高的程序完成这个棘手的任务。
输入格式:
输入为一个字符串,表示报文,包含不超过10000个字母。
输出格式:
输出为一个整数,表示破解出的密文串的长度。
输入样例1:
xabceabcf
输出样例1:
3
输入样例2:
xyabcabcayx
输出样例2:
4
代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
int max = 0;
for (int i = 0; i < str.length(); i ++) {
String newStr = str.substring(i,str.length());
int[] next = makeNext(newStr);
for (int j = 0; j < newStr.length(); j ++) {
if (max < next[j]) {
max = next[j];
}
}
}
System.out.println(max);
}
public static int[] makeNext(String str) {
int j = 0;
int[] next = new int[str.length()];
next[0] = j;
for (int i = 1; i < str.length(); i ++) {
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = next[j - 1];
}
if (str.charAt(i) == str.charAt(j)) {
j ++;
next[i] = j;
}
}
return next;
}
}