題目描述:
給兩個整數(shù)數(shù)組 A 和 B ,返回兩個數(shù)組中公共的矫膨、長度最長的子數(shù)組的長度。
示例:
輸入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
輸出: 3
解釋:
長度最長的公共子數(shù)組是 [3, 2, 1]
/**
* @ClassName: PublicMaxLength
* @Author sandy.n.hao
* @Date: 2018/12/19
* @Version v1.0.0
* @Description: //TODO
*/
public class PublicMaxLength {
public static int count = 0;
public static int tempcount = 0;
public static int getMaxLength(int [] a, int [] b){
for(int i=0; i<b.length; i++)
{
for(int j=0; j<a.length; j++){
tempcount = 0;
if(b[i] == a[j])
{
tempcount++;
compare(a,b,j+1,i+1);
}
if(tempcount > count)
count = tempcount;
}
}
return count;
}
public static int compare(int [] a,int [] b, int la, int lb){
if(la<a.length && lb<b.length){
if(a[la] == b[lb]) {
tempcount++;
compare(a, b, la + 1, lb + 1);
}
}
return tempcount;
}
public static void main(String[] args) {
int [] a = {1,0,0,0,0};
int [] b = {0,0,0,0,1};
System.out.println(getMaxLength(a,b));
}
}