C++ neat and awesome code which may inspire you.


  • 0
    class Solution {
    public:
      void reverseWords(string &s) {
        stripSpaces(s);
        reverse(s.begin(), s.end());
        int i, j;
        for (i = 0, j =  0; j < s.size(); j ++ )
        {
          if (s[j] == ' ')
          {
    	reverse(s.begin() + i, s.begin() + j);
    	i = j + 1;
          }
        }
        reverse(s.begin() + i, s.end());
      }
      void stripSpaces(string &s)
      {
        // Remove leading spaces before a string
        while(s.size() > 0 && s[0] == ' ')
        {
          s.erase(0, 1);
        }
        s += ' ';
        // Remove center space
        for (int i = 0; i < s.size(); i ++)
        {
          while (s[i] == ' ' && s[i + 1] == ' ')
          {
    	s.erase(i, 1);
          }
        }
        // Remove last space
        s.erase(s.size() - 1, 1);
      }
    };
    

  • 0
    L

    Thanks for providing the clean solution. The stripSpaces method could be simplified as

    for(int i = 0; i < s.length(); i++) {
            while (s[i] == ' ' && (s[i+1] == ' ' || i == s.length() - 1 || i == 0))
                    s.erase(i, 1);
    }
    

  • 0

    Sounds interesting, nice advice.


Log in to reply
 

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