常规实现,不用库函数
class Solution {
public:
string ReverseSentence(string str) {
if (str.empty()) {
return str;
}
int left = 0, right = 0;
reverse_str(str, 0, str.size() - 1);
while (right < str.size()) {
while (right < str.size() && str[right] != ' ') {
++right;
}
reverse_str(str, left, right - 1);
left = ++right;
}
return str;
}
private:
void reverse_str(std::string &str, int left, int right) {
if (str.empty()) {
return ;
}
while (left < right) {
char tmp = str[left];
str[left] = str[right];
str[right] = tmp;
++left, --right;
}
}
};