Another solution, written in a more functional style - notice that I'm not allocating new strings in each call to the recursive method (only the split
operation at the beginning allocates new strings). I also took Robert's suggestion of first converting the original problem into a recursion over arrays, it makes things simpler:
public static String longestWord(String s) {
return longestWord(s.split("\\s+"), 0, 0);
}
public static String longestWord(String[] words, int currentIdx, int longestIdx) {
if (currentIdx == words.length)
return words[longestIdx];
return longestWord(words, currentIdx + 1,
words[currentIdx].length() > words[longestIdx].length() ? currentIdx : longestIdx);
}
The trick in the above solution, is that my recursion advances over the indexes of the string array, and not over the strings themselves. That's the reason why I avoid creating new strings at each call. No substring
, copyOfRange
, arraycopy
, new String()
or similar operations are needed, yielding a more elegant solution.
EDIT:
I simplified the above code a little, to make it easier to understand. With regard to the split
method it's a standard string operation, take a look at the documentation.
public static String longestWord(String s) {
return longestWord(s.split(" "), 0, 0);
}
public static String longestWord(String[] words, int currentIdx, int longestIdx) {
if (currentIdx == words.length)
return words[longestIdx];
int idx; // temporarily stores the index of the current longest word
if (words[currentIdx].length() > words[longestIdx].length())
idx = currentIdx;
else
idx = longestIdx;
return longestWord(words, currentIdx + 1, idx);
}