Code:
public class LCS {
static String str1, str2;
static int m, n, c[][];
static char b[][];
public static void main(String[] args) {
if(args.length != 2){
System.out.println("It should take Two Strings");
System.exit(0);
}
str1 = args[0];
str2 = args[1];
m = str1.length();
n = str2.length();
m++;
n++;
c = new int[m][n];
b = new char[m][n];
c[0][0] = 0;
for(int i = 1; i < m ; i++)
c[i][0] = 0;
for(int j = 0; j < n; j++)
c[0][j] = 0;
for(int i = 1; i < m ; i++) {
for(int j = 1; j < n; j++) {
if(str1.charAt(i-1) == str2.charAt(j-1)) {
c[i][j] = c[i-1][j -1] + 1;
b[i][j] = 'S';
} else if(c[i-1][j] >= c[i][j-1]) {
c[i][j] = c[i-1][j];
b[i][j] = 'U';
} else {
c[i][j] = c[i][j-1];
b[i][j] = 'D';
}
}
}
System.out.println("-----------------C Array------------");
for(int i = 0; i < m ; i++) {
for(int j = 0; j < n; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------B Array------------");
for(int i = 1; i < m ; i++) {
for(int j = 1; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
print_LCS(b,m-1,n-1);
}
static void print_LCS(char b[][],int m ,int n){
if(m == 0 || n == 0)
return;
if(b[m][n] == 'S') {
print_LCS(b, m-1, n-1);
System.out.print(str1.charAt(m-1));
} else if (b[m][n] == 'U') {
print_LCS(b, m-1, n);
} else {
print_LCS(b, m, n-1);
}
}
}
public class LCS {
static String str1, str2;
static int m, n, c[][];
static char b[][];
public static void main(String[] args) {
if(args.length != 2){
System.out.println("It should take Two Strings");
System.exit(0);
}
str1 = args[0];
str2 = args[1];
m = str1.length();
n = str2.length();
m++;
n++;
c = new int[m][n];
b = new char[m][n];
c[0][0] = 0;
for(int i = 1; i < m ; i++)
c[i][0] = 0;
for(int j = 0; j < n; j++)
c[0][j] = 0;
for(int i = 1; i < m ; i++) {
for(int j = 1; j < n; j++) {
if(str1.charAt(i-1) == str2.charAt(j-1)) {
c[i][j] = c[i-1][j -1] + 1;
b[i][j] = 'S';
} else if(c[i-1][j] >= c[i][j-1]) {
c[i][j] = c[i-1][j];
b[i][j] = 'U';
} else {
c[i][j] = c[i][j-1];
b[i][j] = 'D';
}
}
}
System.out.println("-----------------C Array------------");
for(int i = 0; i < m ; i++) {
for(int j = 0; j < n; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------B Array------------");
for(int i = 1; i < m ; i++) {
for(int j = 1; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
print_LCS(b,m-1,n-1);
}
static void print_LCS(char b[][],int m ,int n){
if(m == 0 || n == 0)
return;
if(b[m][n] == 'S') {
print_LCS(b, m-1, n-1);
System.out.print(str1.charAt(m-1));
} else if (b[m][n] == 'U') {
print_LCS(b, m-1, n);
} else {
print_LCS(b, m, n-1);
}
}
}
No comments:
Post a Comment