Trim string, split words by whitespace, reverse word order list, and join words with a single space.
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1])
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) sb.append(" ");
}
return sb.toString();
}
}