Given "QA loves Java", return "Java loves QA" — reverse word order, not the characters.
Split on whitespace, then join the tokens in reverse. Handle multiple/leading/trailing spaces by trimming and splitting on a whitespace regex (Python's split() does this by default). O(n).
public static String reverseWords(String s) {
String[] w = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = w.length - 1; i >= 0; i--) {
sb.append(w[i]);
if (i > 0) sb.append(' ');
}
return sb.toString();
}function reverseWords(s) {
return s.trim().split(/\s+/).reverse().join(' ');
}def reverse_words(s):
return ' '.join(s.split()[::-1])Word-order handling shows up in parsing log lines and building readable messages — and probes whether you handle messy whitespace.
Your code returns a leading space for " hello world ". What went wrong?