-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommonSubSequence2dArray.java
More file actions
103 lines (85 loc) · 3.08 KB
/
Copy pathcommonSubSequence2dArray.java
File metadata and controls
103 lines (85 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package MyPractice;
import java.util.ArrayList;
import java.util.List;
public class commonSubSequence2dArray {
static String s1 = "dknkdizqxkdczafixidorgfcnkrirmhmzqbcfuvojsxwraxe";
static String s2 = "dulixqfgvipenkfubgtyxujixspoxmhgvahqdmzmlyhajerqz";
public static void main(String [] args)
{
System.out.println(findCommonSubSequence(s1,s2));
}
public static String findCommonSubSequence(String s1,String s2)
{
char [] s1Array = new char[s1.length()];
for(int i=0;i<s1.length();i++)
{
s1Array[i]=s1.charAt(i);
}
char [] s2Array = new char[s2.length()];
for(int i=0;i<s2.length();i++)
{
s2Array[i]=s2.charAt(i);
}
String commonSubsequqnce = "";
int count=0;
int [][] matrix = new int[s1.length()][s2.length()];
boolean [] alreadyIncrementedColumn = new boolean [s2.length()];
//int max=0;
for(int i=0;i< s1Array.length;i++)
{
boolean alreadyIcremented = false;
for(int j=0;j< s2Array.length;j++)
{
//each row represents the first string and column the second string..maximum match is the maximum of row-1 or col-1
int initialValue = Math.max(matrix[Math.max(0,i-1)][j],matrix[i][Math.max(0,j-1)]);
//System.out.println("Comparing " + s1.charAt(i) + " with " + s2.charAt(j));
if(!alreadyIcremented && !alreadyIncrementedColumn[j] && s1.charAt(i)==s2.charAt(j))
{
if(i==0 || j==0) {
initialValue++;
}
alreadyIcremented = true;
alreadyIncrementedColumn[j]=true;
}
if(i>0 && j>0 && matrix[i][j-1]==matrix[i-1][j] && s1.charAt(i)==s2.charAt(j))
initialValue = matrix[i-1][j-1]+1;
matrix[i][j] = initialValue;
}
}
print2D(matrix);
// Loop through all rows
int max=0;
String sub = "";
for (int i = 0; i < matrix.length; i++) {
// Loop through all elements of current row
for (int j = 0; j < matrix[i].length; j++) {
if(matrix[i][j]>max)
{
sub = sub + s1.charAt(i);
max = matrix[i][j];
}
}
}
System.out.println(max);
return "";
}
public static void print2D(int mat[][])
{
// Loop through all rows
for (int i = -1; i < s1.length(); i++) {
// Loop through all elements of current row
if(i>-1)
System.out.print(s1.charAt(i)+" ");
for (int j = 0; j < s2.length(); j++) {
if(i==-1) {
if(j==0)
System.out.print(" ");
System.out.print(" "+s2.charAt(j));
continue;
}
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
}