力扣151. 反转字符串中的单词

双指针

  • 常规思路:
    • 按照空格split 字符串,得到字符串单词数组;
    • 然后每个单词进行反转(reverse);
    • 然后使用空格将反转后的单词拼接(join)起来;
  • C++ 可以在字符串上直接操作:
    • 先反转字符串;
    • 然后遍历字符串对字符进行操作:
      • 找到单词(非空字符)作为起始 start 指针,找到单词结尾 end 指针;
      • start 到 end 即为单词的区间,对其进行反转操作还原单词;
      • 加上空格字符连接;
    • 最后去除字符串尾部多余的字符,最开始使用 index 指针标记有效字符的位置;
class Solution {
public:string reverseWords(string s) {std::reverse(s.begin(), s.end());int size = s.size();int idx = 0;for (int start = 0; start < size; ++start) {if (s[start] != ' ') {if (idx != 0) {s[idx++] = ' ';}int end = start;while (end < size && s[end] != ' ') {s[idx++] = s[end++];}std::reverse(s.begin() + idx - (end - start), s.begin() + idx);start = end;}}s.erase(s.begin() + idx, s.end());return s;}
};