题目描述
给定两个字符串str1和str2,输出两个字符串的最长公共子序列。如果最长公共子序列为空,则返回"-1"。目前给出的数据,仅仅会存在一个最长的公共子序列。
最长公共子序列:连续的子串
输入描述
输入两个字符串str1和str2。
输出描述
输出两个字符串的最长公共子序列。
Sample Input
1A2C3D4B56
B1D23A456A
Sample Output
123456
如果只求最长公共子序列的长度可以使用空间压缩
1.动态规划找出最长公共子序列的长度
2.利用回溯找出对应长度的公共子序列
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String str1 = bufferedReader.readLine();
String str2 = bufferedReader.readLine();
String str=LCS(str1,str2);
if (str!=null) {
System.out.println(str);
}else {
System.out.println(-1);
}
}
public static String LCS(String s1, String s2) {
int row = s1.length();
int col = s2.length();
int[][] arr = new int[row + 1][col + 1];
for (int i = 1; i < row + 1; i++) {
for (int j = 1; j < col + 1; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
arr[i][j] = arr[i - 1][j - 1] + 1;
} else {
arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
}
}
}
String str = "";
int max = arr[row][col];
if (max == 0) {
return "-1";
} else {
while (row > 0 && col > 0) {
if (s1.charAt(row-1) == s2.charAt(col-1)) {
str = s1.charAt(row-1) + str;
row--;
col--;
max--;
} else if (arr[row][col - 1] > arr[row - 1][col]) {
col--;
} else {
row--;
}
}
}
return str;
}
}