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) {
int n = s.size();
if(n<1) return;
stack<string> words;
string temp = "";
for(int i=0;i<n;i++)
{
if(s[i] != ' ')
temp += s[i];
else
{
if(temp != "")
{ words.push(temp);
temp = "";
}
}
}
if(temp != "")
{
words.push(temp);
}
s = "";
while(!words.empty())
{
s += words.top()+" ";
words.pop();
}
s = s.substr(0,s.size()-1);
return;
}
};