Six lines solution in C++


  • 7
    W
    void reverseWords(string &s) {
        reverse(s.begin(), s.end());
        for (int i = 0, j = 0; i < s.size(); i = j + 1) {
            for (j = i; j < s.size() && !isblank(s[j]); ++j);
            reverse(s.begin()+i, s.begin()+j);
        }
    }

  • -3
    H
    class Solution {
    public:
      void reverseWords(string &s) {
        int len = s.length(), beg = 0, end = len - 1, end2;
        if (len < 2) return;
        while (beg < end) swap(s[beg++], s[end--]);
        beg = end = 0;
        while (end < len)
        {
          while (end < len && s[end] != ' ') ++end;
          end2 = end - 1;
          while (beg < end2) swap(s[beg++], s[end2--]);
          beg = end = end + 1;
        }
      }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.