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) {
string res;
int i=s.size()-1;
while(i>=0)
{
while(s[i]==' '&&i>=0) //去除掉后边的空格
i--;
if(i<0) //去除掉最前边的空格后,i<0也就是说前边没有有用的字符,需要跳出循环
break;
if(!res.empty())
res.push_back(' ');
string temp;
while(s[i]!=' '&&i>=0)
{
temp.push_back(s[i]);
i--;
}
reverse(temp.begin(),temp.end());
res+=temp;
}
s=res;
}
};