Leetcode 151. Reverse Words in a String
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. Return a string of the words in reverse order concatenated by a single space.
Example:
Input: "the sky is blue"
Output: "blue is sky the"
Input: " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Input: "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
s
guaranteed to be non-empty? (Typically, it could be empty so assume it can be.)Here’s the implementation in C++:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::string reverseWords(std::string s) {
// Trim leading and trailing spaces
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
std::istringstream stream(s);
std::string word;
std::vector<std::string> words;
// Split by space and store words in the vector
while (stream >> word) {
words.push_back(word);
}
// Reverse the vector of words
std::reverse(words.begin(), words.end());
// Join words with a single space
std::ostringstream reversedStream;
for (size_t i = 0; i < words.size(); ++i) {
if (i != 0) {
reversedStream << " ";
}
reversedStream << words[i];
}
return reversedStream.str();
}
int main() {
std::string s = " the sky is blue ";
std::cout << "\"" << reverseWords(s) << "\"" << std::endl;
return 0;
}
So, the total time complexity is (O(n)), where (n) is the length of the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?