I have done it finally like what I want. Thank you all for helping and I want to emphasize that it was NOT homework.
public static void main(String[] args) {
String input = "Java is a programming language";
StringTokenizer st = new StringTokenizer(input);
System.out.print(longestWord(input));
}
public static String longestWord(StringTokenizer st) {
if (!st.hasMoreTokens()) {
return "";
} else {
String token = st.nextToken();
String longestInTheRest = longestWord(st);
if (token.length() > longestInTheRest.length()) {
return token;
} else {
return longestInTheRest;
}
The following isn't quite right:
else if (token.length() > result.length()) {
When the above statement executes, result is always " ".
What the function should do is return the larger of: (1) the length of token; (2) the length of the word returned by the recursive call.
You might also think about whether the two s.substring() calls do exactly what you want, or whether there might be a problem. Printing out token and rest (or examining them in a debugger) might be useful.
Since this looks like homework, I'll stop here.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With