例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
class Solution {
public:
string ReverseSentence(string str) {
if("" == str)
return "";
int pre=0;
for(int i=0;i<str.size();i++){
if(str[i]==' ' || i==str.size()-1){
if(i==str.size()-1)
i++;
reverse(str.begin()+pre,str.begin()+i);
pre=i+1;
}
}
reverse(str.begin(),str.end());
return str;
}
};
class Solution {
public:
string ReverseSentence(string str) {
if(str.size() <= 0)
{
return str;
}
reverse(str.begin(),str.end());
//string s1 =" ";
int left=0,right=0;
while ((right = str.find(' ',left)) != string:: npos)
{
reverse(str.begin()+left,str.begin()+right);
left =right + 1;
}
reverse(str.begin()+left,str.end());
return str;
}
};