package org.wjp;
/**
* @author wujunpei
*/
public class Main {
public static void main(String[] args) {
String a = "acac";
String b = "ac";
int[][] length = new int[a.length()][b.length()];
boolean[] flagA = new boolean[a.length()];
boolean[] flagB = new boolean[b.length()];
StringBuilder result = new StringBuilder();
int maxLength = -1;
for (int i = 0; i < a.length(); i++) {
char charA = a.charAt(i);
for (int j = 0; j < b.length(); j++) {
char charB = b.charAt(j);
if (charA == charB) {
if (i == 0 || j == 0) {
length[i][j] = 1;
} else {
length[i][j] = length[i - 1][j - 1] + 1;
}
if (maxLength < length[i][j]) {
maxLength = length[i][j];
}
if (!flagA[i] && !flagB[j]) {
result.append(charA);
flagA[i] = true;
flagB[j] = true;
}
} else {
int zuo = j == 0 ? 0 : length[i][j - 1];
int shang = i == 0 ? 0 : length[i - 1][j];
length[i][j] = Math.max(zuo, shang);
}
}
}
System.out.println(result);
}
}
【Java】最长公共子序列
最新推荐文章于 2023-04-06 15:39:06 发布