class Solution:
def reverseWords(self, s: str) -> str:
# Split the string into words, removing extra spaces
words = s.strip().split()
# Reverse the list of words
words.reverse()
# Join the words with a single space
return ' '.join(words)
class Solution {
public:
string reverseWords(string s) {
istringstream iss(s);
vector<string> words;
string word;
while (iss >> word) {
words.push_back(word);
}
reverse(words.begin(), words.end());
string result;
for (int i = 0; i < words.size(); ++i) {
if (i > 0) result += " ";
result += words[i];
}
return result;
}
};
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();
}
}
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
return s.trim().split(/\s+/).reverse().join(' ');
};
You are given a string s
that may contain leading, trailing, or multiple spaces between words. Your task is to reverse the order of the words in s
. A word is defined as a sequence of non-space characters. The returned string should have words separated by a single space, and there should be no leading or trailing spaces.
Example:
Input: s = " the sky is blue "
Output: "blue is sky the"
The core of this problem is to reverse the order of words in a string, while also cleaning up any extra spaces. Initially, you might think about reversing the characters of the entire string and then reversing each word, but this can get tricky with the spaces.
Instead, a simpler approach is to:
The brute-force method would involve manually parsing the string character by character, handling spaces, and building the result, but using language features like split()
and join()
makes the solution much cleaner and less error-prone.
Here’s a step-by-step breakdown of the efficient approach:
Why this design?
Input: s = " hello world! "
"hello world!"
["hello", "world!"]
["world!", "hello"]
"world! hello"
Notice how all extra spaces are removed and the words are in the correct reversed order.
The key to solving "Reverse Words in a String" efficiently is to leverage built-in string and array methods to handle splitting, reversing, and joining. This approach avoids manual parsing and makes the code concise and readable. By focusing on extracting words and then reversing their order, we ensure that all spacing issues are handled automatically, resulting in a clean and elegant solution.