import java.util.Scanner;
class Main {
static int n;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String text1=sc.next();
String text2=sc.next();
char[] t1=text1.toCharArray();
char[] t2=text2.toCharArray();
int[][]c=new int[t1.length+1][t2.length+1];
char[][]B=new char[t1.length+1][t2.length+1];
B=f(t1,t2,c,B);
System.out.println(n);
print(t1,t1.length,t2.length,B);
}
public static char[][] f(char[] t1, char[] t2, int[][] c, char[][] B){
for (int i = 1; i <= t1.length; i++) {
c[i][0]=0;
}
for (int j = 1; j <= t2.length; j++) {
c[0][j]=0;
}
for (int i = 1; i <= t1.length; i++) {
for (int j = 1; j <= t2.length; j++) {
if(t1[i-1]==t2[j-1]){
c[i][j]=c[i-1][j-1]+1;
B[i][j]='↖';
}
else if(c[i-1][j]>=c[i][j-1]){
c[i][j]=c[i-1][j];
B[i][j] = '↑';
}
else {
c[i][j]=c[i][j-1];
B[i][j] = '←';
}
}
}
n=c[t1.length][t2.length];
return B;
}
public static void print(char[] X,int i,int j,char[][] B){
if(i==0||j==0)
return;
if(B[i][j]=='↖'){
print(X,i-1,j-1,B);
System.out.print(X[i-1]);
}
else if(B[i][j]=='↑'){
print(X,i-1,j,B);
}
else{
print(X,i,j-1,B);
}
}
}
dp 最公共子序列
最新推荐文章于 2024-09-04 21:39:45 发布