// 翻转单词顺序序列
// 先翻转所有单词,再逐个单词翻转
string ReverseSentence(string str) {
if (str.size() == 0) {
return " ";
}
Reverse(str, 0, str.size() - 1); //翻转所有单词
int left = 0, right = 0;
while (right <= str.size()) {//逐个单词翻转
if ((str[right] == ' ') || (right == str.size() && str.size() -1) != ' ') {
/*for (int i = 0; i < right; i++) { // 遇见空格和字符串最后一个位置
cout << str[i] << ' ';
}*/
Reverse(str, left, right - 1);
left = right + 1;
}
right++;
}
return str;
}
void Reverse(string &str, int left, int right) {
while (left < right) {
char temp = str[left];
str[left] = str[right];
str[right] = temp;
//swap (str[left], str[right]);
left++;
right--;
}
}