描述
You are given a sequence of integers, A = a1, a2, ... an. A consecutive subsequence of A (say ai, ai+1 ... aj) is called a "repeated sequence" if it appears more than once in A (there exists some positive k that ai+k = ai, ai+k+1 = ai+1, ... aj+k = aj) and its appearances are not intersected (i + k > j).
Can you find the longest repeated sequence in A?
输入
Line 1: n (1 <= n <= 300), the length of A.
Line 2: the sequence, a1 a2 ... an (0 <= ai <= 100).
输出
The length of the longest repeated sequence.
5 2 3 2 3 2
2
题目很简单,直接贴代码
import java.util.Scanner;
public class ms20142 {
/**
* @http://blog.csdn.net/amazure
* 微软编程一小时 第二题
* 思路比较简单 暴力循环 应该有更好的方法
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
int length = 0;
for (int i = 0; i < a.length; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + length + 1; j < a.length; j++) {//j=i+length+1 对算法的一个小优化
int k = 0;
while (i + k < j && j + k < a.length) {
if (a[i + k] == a[j + k]) {
k++;
} else {
break;
}
}
length = Math.max(k, length);
}
}
System.out.println(length);
}
}