简体   繁体   中英

Java StackOverFlowError - Bad Recursive Call?

I'm given a set of strings called "dictionary", stored as a field, which represents a dictionary of words.

I am to write a method which accepts a String parameter ("phrase") and returns a set containing all the words in the dictionary set that can be made from rearranging the characters in the given phrase. Basically I'm searching the dictionary for anagrams.

Here is my code:

public Set<String> getWords(String phrase) {
    Set<String> anagrams = new TreeSet<String>();
    String chosen = "";
    anagrams.addAll(getWords(phrase, chosen));
    return anagrams;
}

public Set<String> getWords(String phrase, String chosen) {
    if (phrase == null) {
        throw new IllegalArgumentException();
    } 
    Set<String> anagrams = new TreeSet<String>();
    if (dictionary.contains(chosen)) {
        anagrams.add(chosen);
        anagrams.addAll(getWords(phrase, chosen));
    } else {
        for (int i = 0; i < phrase.length(); i++) {
            String ch = phrase.substring(i, i + 1);         
            String temp = phrase.substring(0, i) + phrase.substring(i + 1);
            anagrams.addAll(getWords(temp, chosen + ch));
        }
    }
    return anagrams;
}    

So my approach is to: 1. Check the dictionary for the possibility passed in this thread, represented by the variable "chosen."

  1. If the dictionary does contain the possibility, add it to the set called "anagrams" which is returned at the end of the call. Then pass the possibility again to try to make other combinations out of it.

3.. If the dictionary does not contain the possibility, modify the string to try other possibilities, which are then tested recursively.

The code above produces a "stack overflow error", which my research indicates means I'm doing infinite recursion, or passing the same string over and over again infinitely. I can't see where I'm doing this, though. Can you?

public Set<String> getWords(String phrase, String chosen) {
    //...
    if (dictionary.contains(chosen)) {
        anagrams.add(chosen);
        anagrams.addAll(getWords(phrase, chosen)); //<--here we are

You're making recursive call with exactly the same parameters. And you don't do anything that would make the condition return false next time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM