EDIT: UP
The code does not work properly with the strings below.
"1 11 23 1 18 9 15 23 5"
"11 1 18 1 20 5 11 1"
EDIT: I noticed, that if I change 20 to 40 in second string, the function works properly...
For strings:
"12 4 55 11 8 43 22 90 5 88 15"
"15 66 4 36 43 22 78 88 32"
it works properly. Where is the problem?
Here is my code:
int[][] tabelka = new int[linia1.length()+1][linia2.length()+1];
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
if ( linia1.charAt(i) == linia2.charAt(j) ) {
tabelka[i+1][j+1] = tabelka[i][j] + 1;
}
else {
tabelka[i+1][j+1] = Math.max(tabelka[i+1][j], tabelka[i][j+1]);
}
}
}
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
System.out.println(tabelka[i][j]);
}
}
StringBuffer podciag = new StringBuffer();
for(int x = linia1.length(), y = linia2.length(); x != 0 && y != 0; ) {
if( tabelka[x][y] == tabelka[x-1][y] ) {
licznik++;
x--;
}
else if( tabelka[x][y] == tabelka[x][y-1] ) {
licznik++;
y--;
}
else {
licznik++;
assert linia1.charAt(x-1) == linia2.charAt(y-1);
podciag.append(linia1.charAt(x-1));
x--;
y--;
}
}
String buff = podciag.reverse().toString();
The output of this code (for the first two strings) is:
11 1 18 1 2 5
However, the output should be:
11 1 18 5
For a full / better explanation, please refer to:
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
http://www.geeksforgeeks.org/printing-longest-common-subsequence/
I think that you are constructing the array correctly. However, I am not sure about the way the table is being read in order to construct the LCS.
The idea is to start at the end of the 2D array solution[str1.length()][str2.length()] and if: