Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
class Solution {
public:
void reverseWords(string &s) {
if (s.size() == 0)
return;
string result = "";
if (s[s.size() - 1] == ' ') {
int last = s.find_last_not_of(' ') + 1;
s.erase(last, s.size() - last);
}
int first = s.find_first_not_of(' ', 0);
while (first != string::npos) {
int last = s.find(' ', first);
if (last == string::npos)
last = s.size();
string word = s.substr(first, last - first);
reverse(word.begin(), word.end());
result += word;
first = s.find_first_not_of(' ', last);
if (first == string::npos)
break;
result += ' ';
}
reverse(result.begin(), result.end());
s.swap(result);
}
};