longest common subsequence function does not work for all examples

橙三吉。 提交于 2019-12-11 18:59:59

问题


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:


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:

  • 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.


来源:https://stackoverflow.com/questions/27153957/longest-common-subsequence-function-does-not-work-for-all-examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!