goal: print out all the longest common subsequences of a given string.
example: first line: acb, second line abc; output result: ac,ab
correct program:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LCS {
private static int[][] dp;
private static String s1, s2;
private final static Set<String> set = new HashSet<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
s1 = in.nextLine(); int len1 = s1.length();
s2 = in.nextLine(); int len2 = s2.length();
//dp
dp = new int[len1+1][len2+1];
for (int i = 1; i < len1+1; iPP) {
for (int j = 1; j < len2+1; jPP) {
if (s1.charAt(i-1) == s2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
//dp
for (int i = 0; i < len1+1; iPP) {
for (int j = 0; j < len2+1; jPP) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
//LCS
String res = "";
traceBack(len1, len2, res);
System.out.println(set.toString());
}
private static void traceBack(int len1, int len2, String res) {
while (len1 > 0 && len2 > 0) {
if (s1.charAt(len1-1) == s2.charAt(len2-1)) {
res += s1.charAt(len1-1);
//res.append(s1.charAt(len1-1));
len1--; len2--;
} else {
if (dp[len1][len2-1] > dp[len1-1][len2]) {
len2--;
} else if (dp[len1][len2-1] < dp[len1-1][len2]) {
len1--;
} else {
traceBack(len1-1, len2, res);
traceBack(len1, len2-1, res);
return;
}
}
}
set.add(new StringBuilder(res).reverse().toString());
}
}
error code, ask the boss for advice:
example: first line: acb, second line abc; output result: what"s wrong with the ac,abac, solution? Thank you
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* :StringBuilderString
*/
public class LCS {
private static int[][] dp;
private static String s1, s2;
private final static Set<String> set = new HashSet<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
s1 = in.nextLine(); int len1 = s1.length();
s2 = in.nextLine(); int len2 = s2.length();
//dp
dp = new int[len1+1][len2+1];
for (int i = 1; i < len1+1; iPP) {
for (int j = 1; j < len2+1; jPP) {
if (s1.charAt(i-1) == s2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
for (int i = 0; i < len1+1; iPP) {
for (int j = 0; j < len2+1; jPP) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
//LCS
StringBuilder res = new StringBuilder();
traceBack(len1, len2, res);
System.out.println(set.toString());
}
private static void traceBack(int len1, int len2, StringBuilder res) {
while (len1 > 0 && len2 > 0) {
if (s1.charAt(len1-1) == s2.charAt(len2-1)) {
res.append(s1.charAt(len1-1));
len1--; len2--;
} else {
if (dp[len1][len2-1] > dp[len1-1][len2]) {
len2--;
} else if (dp[len1][len2-1] < dp[len1-1][len2]) {
len1--;
} else {
traceBack(len1-1, len2, res);
traceBack(len1, len2-1, res);
return;
}
}
}
set.add(new StringBuilder(res).reverse().toString());
}
}