C++ Commented - Concise - One Pass 8ms O(n)


  • 0
    S
    void reverseWords(string &s) {
    	int len = s.length();
    	if (len == 0) return;
    
    	reverse(s.begin(), s.end()); int j = 0;
    	for (int i = 0; i < len; ++i) {
    		// reverse the substrings from the start
    		if (s[i] == ' ') reverse(s.begin() + j, s.end() - (len - i)); j = i + 1; 
    	}
    	// reverse the last substring since we dont have a space there we know its still left to reverse
    	reverse(s.begin() + j, s.end());
    }

Log in to reply
 

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