I had a technical interview and was given the following question:
Write a function that takes a sentence and returns the sentence with the words in reverse order (i.e. "hello world" becomes "world hello").
Here is the solution that I gave in Java:
/** Takes a sentence as an input and returns the sentence with the words in
* reversed order. */
private static String reverseSentence(String sentence) {
String[] words = sentence.split("\\s+");
String reversedString = "";
for (int k = words.length - 1; k >= 0; k -= 1) {
reversedString += " " + words[k];
}
return reversedString.substring(1);
}
I got to thinking that there has to be a more efficient way to solve this problem than this. I don't see this being asked in a technical interview for a top company if this solution turns out to be the best one and there isn't one more efficient/elegant.
Can anyone think of a better way to do this?