思路:
先对整体的句子进行翻转,然后对句子的每个单子进行翻转
class Solution {
public:
string ReverseSentence(string str)
{
int length = str.length();
if(length == 0)
return "";
reverse(str, 0, length - 1);//整体句子翻转
int i = 0;
int s,e;//分别指向翻转部分的起点和终点
while(i < length)
{
while(i < length && str[i] == ' ')//过滤掉空格
i++;
s = i;//空格后的第一个字符
while(i < length && str[i] != ' ')//找到字符的结尾
i++;
e = i - 1;
reverse(str, s, e);//局部翻转
}
return str;
}
//翻转s的startt~end的字符
void reverse(string & s, int start, int end)
{
string temp = s;
int p = start;
for(int i = end; i >= start; i--)
{
temp[p] = s[i];
p++;
}
s = temp;
}
};