这道题的思路就是先把整个字符串逆置,再对每个单词逆置。
以 I like beijing.为例,先把这个字符串整个逆置,字符串变成 .gnijieb ekil I 然后对每个单词逆置字符串变成 beijing. like I
图演示如下
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin,str);
reverse(str.begin(),str.end());
string::iterator start = str.begin();
while (start != str.end())
{
auto end = start;
while (end != str.end() && *end != ' ')
{
++end;
}
reverse(start,end);
if (end != str.end()){
start = end + 1;
}
else {
start = end;
}
}
cout << str << endl;
return 0;
}