最长公共子序列(java)模板

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Agxyzx/article/details/98987386

最长公共子序列(java)模板
时间复杂度O(n*m)

import java.util.Scanner;

public class 最长公共子序列 {
static int book[][];

public static int lcslength(char x[], char y[]) {
	int m = x.length - 1;
	int n = y.length - 1;
	int c[][] = new int[m + 1][n + 1];

	for (int i = 1; i <= m; i++)
		c[i][0] = 0;
	for (int i = 1; i <= n; i++)
		c[0][i] = 0;
	for (int i = 1; i <= m; i++) {
		for (int j = 1; j <= n; j++) {
			if (x[i] == y[j]) {
				c[i][j] = c[i - 1][j - 1] + 1;
				book[i][j] = 1;
			} else if (c[i - 1][j] >= c[i][j - 1]) {
				c[i][j] = c[i - 1][j];
				book[i][j] = 2;
			} else {
				c[i][j] = c[i][j - 1];
				book[i][j] = 3;
			}
		}
	}
	return c[m][n];

}

public static void lcs(int i, int j, char x[]) {
	if (i == 0 || j == 0)
		return;
	if (book[i][j] == 1) {
		lcs(i - 1, j - 1, x);
		System.out.print(x[i]);
	} else if (book[i][j] == 2)
		lcs(i - 1, j, x);
	else
		lcs(i, j - 1, x);
}

public static void main(String args[]) {
	Scanner sc = new Scanner(System.in);
	String A = sc.next();
	String B = sc.next();

	int m = A.length();
	int n = B.length();
	char a[] = new char[m + 1];
	char b[] = new char[n + 1];
	for (int i = 1; i <= m; i++) {
		a[i] = A.charAt(i - 1);
	}
	for (int i = 1; i <= n; i++) {
		b[i] = B.charAt(i - 1);
	}
	book = new int[m + 1][n + 1];

	lcslength(a, b);
	lcs(m, n, a);

}

}

展开阅读全文

没有更多推荐了,返回首页