标签:param out rgs 动态规划 实现 void 信息 test cab
public class Test2 {
static int[][] result;
static String str1 = "ABCBDAB";
static String str2 = "BDCABA";
static char[][] b;
public static void main(String[] args) {
result = new int[str1.length()+1][str2.length()+1];
b = new char[str1.length() + 1][str2.length() + 1];
LCS(str1, str2);
for (int i = 0; i < str1.length()+1; i++) {
for (int j = 0; j < str2.length()+1; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
System.out.println("最大公共子序列的长度为:" + result[str1.length()][str2.length()]);
System.out.println("最大公共子序列为:");
print_LCS(str1.length(), str2.length());
}
/**
* 求出最大公共子序列的长度 并记录构造表信息
* @param str1
* @param str2
*/
static void LCS(String str1, String str2) {
/*
* 初始化二位数组的边界
*/
for (int i = 0; i <= str1.length(); i++) {
result[i][0] = 0;
}
for (int i = 0; i <= str2.length(); i++) {
result[0][i] = 0;
}
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
if(str1.charAt(i - 1) == str2.charAt(j - 1)) {
result[i][j] = result[i - 1][j - 1] + 1;
b[i][j] = ‘↖‘;
} else if(result[i - 1][j] >= result[i][j-1]) {
result[i][j] = result[i - 1][j];
b[i][j] = ‘↑‘;
} else {
result[i][j] = result[i][j - 1];
b[i][j] = ‘←‘;
}
}
}
}
/**
* 打印构造表信息
* @param i
* @param j
*/
static void print_LCS(int i, int j) {
if(i == 0 || j == 0) {
return;
}
if(b[i][j] == ‘↖‘) {
print_LCS(i-1, j-1);
System.out.print(str1.charAt(i-1));
} else if(b[i][j] == ‘↑‘) {
print_LCS(i-1, j);
} else {
print_LCS(i, j-1);
}
}
}
标签:param out rgs 动态规划 实现 void 信息 test cab
原文地址:https://www.cnblogs.com/fsmly/p/10046715.html