0

In contrast to findet the longest common subsequence in Strings I can't add arrays as simple as with Strings, which makes the problem harder for me.

The code marked with * just illustrates what I want to achieve.

Is this possible without the use of additional dependencies?

static long[] lgs(long[] x, long[] y) {

    if ((x.length == 0 || y.length == 0)) {
        return new long[] {};
    }

    else if (x[x.length-1] == y[y.length -1]) {
        System.out.println(x[x.length-1]);
        return *x[x.length -1] +* lgs(Arrays.copyOf(x, x.length -1), Arrays.copyOf(y, x.length-1));
    }

    else {
        long[] s1 = lgs(Arrays.copyOf(x, x.length -1), y);
        long[] s2 = lgs(x, Arrays.copyOf(y, y.length-1));
        return (x.length > y.length) ? s1 : s2;
    }
}
Paul Ahuevo
  • 131
  • 1
  • 2
  • 13
  • Possible duplicate of [How can I concatenate two arrays in Java?](http://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java) – Bernhard Barker May 13 '17 at 10:30
  • for clarification: I found the thread and it works like that. I was wondering if there is another solution to the problem without dependencies or new functions. – Paul Ahuevo May 13 '17 at 10:35
  • Another solution to the longest common subarray problem or the problem of concatenating arrays? [There are well-known solutions to the former](https://en.wikipedia.org/wiki/Longest_common_substring_problem) - the code for substring and subarray will look almost identical. The question linked above provides plenty of ways to concatenate arrays, some of which should only add like 3 lines to your function with no additional dependencies. – Bernhard Barker May 13 '17 at 10:43
  • As far as I understand I always need to declare new variables in order to concatenate. As there is a recursive call I think this will lead to problems. – Paul Ahuevo May 13 '17 at 11:15
  • If you're worried about memory usage, declaring a variable to store the array you want to return isn't going to affect your memory usage much. If you're worried about it not working, you're doing basically the same thing 3 lines further down - `long[] s1 = ...; ... return ... s1` - it's not a problem, Java won't get rid of an object you're using even if the original variable you used to store it goes out of scope. – Bernhard Barker May 13 '17 at 11:31
  • Thank you very much, you helped me a lot. I thought the variables i declare would be overwritten if I call them again, so I thought I have to pack everything into return. – Paul Ahuevo May 13 '17 at 12:04

0 Answers0