描述
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解法:使用DP,d[i][j]表示分别以i和j结尾的相同子串的长度,为了不相交j-d[i-1][j-1]>i
public void func(int [] num){
int len = num.length;
int[][] d = new int[len][len];
int max = 0;
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
if(num[i] == num[j]){
if(i==0 || (j-d[i-1][j-1] <= i)){
d[i][j] = 1;
}
else{
d[i][j] = d[i-1][j-1] + 1;
}
if(d[i][j] > max) max = d[i][j];
}
else d[i][j] = 0;
}
}
System.out.println(max);
}