Printing Longest Common Subsequence
import java.util.Scanner;
class LongestCommonSequencePrint{
public static String cal(String x, String y, int n ,int m){
int t[][]=new int[n+1][m+1];
for(int i=0;i<n+1;i++){
for(int j=0;j<m+1;j++){
if(n==0 || m==0){
t[i][j]=0;
}
}
}
for(int i=01;i<n+1;i++){
for(int j=01;j<m+1;j++){
if(x.charAt(i-1)==y.charAt(j-1)){
//t[n][m]=1+cal(x,y,i-1,j-1);
//t[i][j]=1+cal(x,y,i-1,j-1);
t[i][j]=t[i-1][j-1]+1;
}
else{
//t[n][m]=Integer.max((cal(x,y,i-1,j)),cal(x,y,i,j-1));
//t[i][j]=Integer.max((cal(x,y,i-1,j)),cal(x,y,i,j-1));
t[i][j]=Integer.max(t[i][j-1],t[i-1][j]);
}
}
}
String s=print(x,y,n,m,t);
return s;
}
public static String print(String x, String y, int n, int m, int[][]t){
StringBuilder sb=new StringBuilder();
int i=n;
int j=m;
while(i>0 && j>0){
if(x.charAt(i-1)==y.charAt(j-1)){
sb.append(x.charAt(i-1));
i--;
j--;
}
else{
if(t[i-1][j]>t[i][j-1]){
i--;
}
else{
j--;
}
}
}
//System.out.println((sb.reverse()).toString());
return (sb.reverse()).toString();
}
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
String x=sc.next();
String y=sc.next();
int n=x.length();
int m=y.length();
String a=cal(x,y,n,m);
System.out.println(a);
}
}
Thanks for Reading😇.
"Share further to increase knowledge treasure.😊"
Comments
Post a Comment