LCS(代码填空题)

LCS即最长公共子序列,是两个序列所有相同子序列中,最长的几个子序列称为最长公共子序列。

列如序列 abcd 和序列 adb 的最长公共子序列是ab 和 ad 。虽然最长公共子序列不是唯一的,但是最长公共子序列的长度却是唯一的。

下面一段代码就是计算两个序列的最长公共子序列的长度。

代码框中的代码是一种实现,请分析并填写缺失的代码。

package 蓝桥杯2018年B组第二次模拟赛;

import java.util.*;
import java.math.*;

public class LCS{
    public static final int N = 10010;
    public static int[] f = new int[N];
    public static char[] a = new char[N];
    public static char[] b = new char[N];
    public static int max(int x, int y) {
        if (x > y) {
            return x;
        }
        return y;
    }
    public static int lcs() {
        for (int i = 0; i < a.length; ++i) {
            for (int j = 0, ans = 0; j < b.length; ++j) {
                int tmp = f[j];
                if (a[i] == b[j]) {
                    /*在这里填写必要的代码*/
                    //f[j]=(j>0?f[j-1]+1:1);
                    f[j]=ans+1;
                }
                else if ( j - 1 > 0 ) {
                    f[j] = max(f[j], f[j - 1]);
                }
                ans = tmp;
            }
        }
        return f[b.length - 1];
    }

    public static void main(String[] args)
    {
        Scanner cin = new Scanner(System.in);
        String x = cin.next();
        String y = cin.next();
        a = x.toCharArray();
        b = y.toCharArray();
        System.out.println(lcs());
    }
}

 

posted @ 2018-03-24 17:25  henu小白  阅读(359)  评论(0编辑  收藏  举报