longest common subsequence function does not work for all examples

170 views Asked by At

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
1

There are 1 answers

0
alampada On BEST ANSWER

For a full / better explanation, please refer to:

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:

  • The last characters of str1 and str2 are equal then the last character is part of the LCS and decrement both indexes
  • If they are not equal, compare solution[i-1][j] and solution[i][j-1] and go in direction of greater value.
  • Repeat until either of the indexes are 0.