You are on page 1of 1

LCS.

java
import java.io.*;
import java.util.*;
class LCS
{
public static void main(String[] args)throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter Two Strings");
String x=in.readLine();
String y=in.readLine();
int M=x.length();
int N=y.length();
int[][] opt=new int[M+1][N+1];
for(int i=M-1;i>=0;i--)
{
for(int j=N-1;j>=0;j--)
{
if(x.charAt(i)==y.charAt(j))
opt[i][j]=opt[i+1][j+1]+1;
else
opt[i][j]=Math.max(opt[i+1][j],opt[i][j+1]);
}
}
System.out.println("LCS Output:");
int i=0,j=0;
while(i<M && i<N)
{
if(x.charAt(i)==y.charAt(j))
{
System.out.print(x.charAt(i));
i++;
j++;
}
else if(opt[i+1][i]>=opt[i][i+1])i++;
else j++;
}
System.out.println();
}
}

Page 1

You might also like