使用快慢指针,注意循环结束后快指针比慢指针大的情况,此时应该将最后一个单词加入到结果中
class Solution { public: string reverseWords(string s) { if (s.empty()) { return s; } int start = -1; vector<string> result_vec; string result; for (int i = 0; i < s.size(); i++) { if (s[i] != ' ') { start = i; break; } } if (start == -1) { return result; } int slow = start; int fast = start; while (fast < s.size()) { if (s[slow] != ' ' && s[fast] != ' ') { fast++; } else if (s[slow] != ' ' && s[fast] == ' '){ result_vec.emplace_back(s.substr(slow, fast - slow)); slow = fast; } else if (s[slow] == ' ' && s[fast] == ' ') { slow++; fast++; } } if (fast > slow) { result_vec.emplace_back(s.substr(slow, fast - slow)); } for (int i = result_vec.size() - 1; i > 0; i--) { result = result + result_vec[i] + " "; } return result + result_vec[0]; } };