美文网首页
小练习(一)

小练习(一)

作者: Sandy_678f | 来源:发表于2018-12-19 20:03 被阅读0次

题目描述:
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。

示例:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出: 3
解释:
长度最长的公共子数组是 [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));
    }
}

相关文章

网友评论

      本文标题:小练习(一)

      本文链接:https://www.haomeiwen.com/subject/nirskqtx.html