3-line C++ code, in-place operation, 6ms, using string functionalities.


  • 1
    M

    simple and straightforward steps:

    1. reverse the whole string;
    2. reverse back each word;
    void reverseWords(string &s) {
            reverse(s.begin(), s.end());
            for (int i, j = 0; (i = s.find_first_not_of(" ", j)) != -1;)
                reverse(s.begin() + i, s.begin() + ((j = s.find(' ', i)) == -1 ? j = s.size() : j));
        }
    

  • 0
    C

    @milangel

    While it is safer to use functions from standard library, one may be asked to implement the reverse function by him/her self because it is very straightforward. The following lines of code are my implementaiton

    void reverseImpl(string &s, size_t start, size_t len) {
      for (int i = start; i < start + (len / 2); ++i) {
        size_t end = start * 2 + len - i - 1;
        char c = s[i];
        s[i] = s[end];
        s[end] = c;
      }        
    }
    

Log in to reply
 

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