对于作业,我应该使用递归找到句子中最长的单词。我写了一个方法,它取句子的前两个词,比较它们,然后取两者中较长的一个,并将其与句子其余部分的下一个词进行比较。我的逻辑检查出来了,但该方法无法正常工作。我认为有一种侥幸会占用空间,这就是它不起作用的原因。
public static String longestWord(String sentence)
{
if (sentence.indexOf(' ') == -1) { // IF sentence only has one word
return sentence;
}
String word1 =(sentence.indexOf(" ") != -1)? sentence.substring(0, sentence.indexOf(" ")):
sentence.substring(0);
String temp = sentence.substring(sentence.indexOf(" ")+1);
String word2 = null;
String rest = null;
if (sentence.indexOf(" ") != -1) {
word2 = (temp.indexOf(" ") != -1)? temp.substring(0, temp.indexOf(" ")+1):
temp.substring(0);
rest = temp.substring(temp.indexOf(" ")+1);
}
if (word1.length() > word2.length()) {
return longestWord(word1 + rest);
}
if (word2.length() > word1.length()) {
return longestWord(word2 + rest);
}
return sentence;
}