0

I need some help in JAVA: I have a function signature which I can't change, and my function needs to be recursive and to return String array without any option to add it to the signature.

This is the signature I've got:

public String[] findSimilar(String w, int index, int k)

The function looks for similar words in a TRIE structure, with a difference of K letters changes between them.

For example- in a TRIE withe the words hello, nice, nine, cry, for the word "bike" and k=2, the function will return a String[] with nice and nine.

I'm not looking for a solution, just for a method to return string array.

** I wrote a function with the signature I've received as a wrapper, but I just found out that I can't use wrapper.

Thank you!

1
  • If the Strings are in a collection you can return collection.toArray(new String[0]); Commented Dec 19, 2013 at 8:59

3 Answers 3

1

The trivial example:

public String[] findSimilar(String w, int index, int k) {
    return new String[] {"string1","string2"}
}

Maybe more useful:

public String[] findSimilar(String w, int index, int k) {
    List<String> similar = new ArrayList<>();
    // insert some implementation here

    return similar.toArray(new String[similar.size()]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not looking for a solution, just for a method to return string array.

To return a string array with literals string1 and string2 you could just use an array initializer such as return new String[] { "string1", "string2"};

Else, you could just create the String array and assign values to its positions if you know beforehand how many elements you will be returning:

String[] arr = new String[2];
arr[0] = "string1";
arr[1] = "string2";
return arr;

If it's the return type of a recursive function, you'll probably need to use the result from the recursive call to build your own result in the current call. Taking into account arrays cannot be extended, you'll need to create a new one with the expected size, and copy the values of the result into it for instance with System.arraycopy.

Comments

0

Use something like this. I would not like to provide full code just an idea

public String[] findSimilar(String w, int index, int k) {
    String[] res1=findSimilar(conditions one);
    String[] res2=findSimilar(conditions two);

    String[] res=new String[res1.length+res2.length];
    //use public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
    System.arraycopy(copyFrom, ..., copyTo, ..., ...);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.