整体翻转,再每个单词翻转
class Solution {
public:
string ReverseSentence(string str) {
reverse(str.begin(),str.end());
int i=0,j=0;
while(i<str.length())
{
while(j<str.length()&&str[j]!=' ')j++;
reverse(str.begin()+i,str.begin()+j);
i=++j;
}
return str;
}
};
分词然后加起来
class Solution {
public:
string ReverseSentence(string str) {
string ans="",temp="";
for(int i=0;i<str.length();i++)
{
if(str[i]==' ')ans=" "+temp+ans,temp="";
else temp+=str[i];
}
ans=temp+ans;
return ans;
}
};