Reverse Words in a String
Problem
Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
s = " the quick brown fox ""fox brown quick the"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;
}
Explanation
This one flips the order of the words, not the letters, and tidies up any messy spacing along the way. The whole job is really three small steps: split, reverse, join.
First we tokenize on whitespace. Plain s.split() in Python automatically drops leading, trailing, and repeated spaces, leaving a clean list of words. (The JS version uses .filter(Boolean) to throw away the empty pieces that extra spaces create.)
Then we reverse that list of words, and finally join them back together with exactly one space between each. That guarantees the output has no stray double spaces or edge spaces.
Example: " the quick brown fox ". Splitting gives the tokens [the, quick, brown, fox]. Reversing makes it [fox, brown, quick, the], and joining with single spaces yields "fox brown quick the".
Each character is processed a constant number of times during splitting and joining, so the work grows linearly with the length of the string.