Reverse the Words in a Sentence

medium string

Problem

Reverse the order of whitespace-separated words in a string and collapse all stretches of internal whitespace to a single space. Leading and trailing whitespace must be removed.

Inputs = " the quick brown fox "
Output"fox brown quick the"
Tokenize on whitespace, drop empties, reverse, then join with one space.

def reverse_words(s):
    return " ".join(reversed(s.split()))
function reverseWords(s) {
  return s.split(/\s+/).filter(Boolean).reverse().join(" ");
}
class Solution {
    public String reverseWords(String s) {
        String[] tokens = s.trim().split("\\s+");
        Collections.reverse(Arrays.asList(tokens));
        return String.join(" ", tokens);
    }
}
string reverseWords(string s) {
    vector<string> tokens;
    stringstream ss(s);
    string w;
    while (ss >> w) tokens.push_back(w);
    reverse(tokens.begin(), tokens.end());
    string out;
    for (int i = 0; i < (int)tokens.size(); i++) {
        if (i) out += " ";
        out += tokens[i];
    }
    return out;
}
Time: O(n) Space: O(n)