Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
小trick:在for循环里,添加while循环。
class Solution {
public:
void reverseWords(string &s)
{
//从前往后扫描
string res, word;
for(int i = s.size()-1; i >= 0;)
{
while(i >= 0 && s[i] == ' ')--i;//去掉空格
if(i < 0)break;
if(res.size() != 0)res.push_back(' ');
word.clear();
while(i >= 0 && s[i] != ' ')word.push_back(s[i--]);//word为找到的一个单词
for(int j = word.size()-1; j >= 0; --j)
res.push_back(word[j]);
}
s = res;
}
};