Any advice to optimize my two-pass-reverse solution in 12 ms?


  • 0
    X
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    class Solution 
    {
    public:
    
    	void reverseWords(string &s)
    	{
            int wordLength = 0;
    		auto wordBegin = s.begin();
    		for (auto wordEnd = wordBegin; wordEnd < s.end(); wordEnd++)
    		{
    			if (*wordEnd != ' ')
    			{
    			    // The left border of a word is encountered.
    				if (wordLength == 0 && wordBegin > s.begin())
    					wordBegin++;
    				wordLength++;
    				// The right border of a word is encountered.
    				if (wordEnd + 1 == s.end() || *(wordEnd + 1) == ' ')
    				{
    					std::reverse(wordBegin, wordEnd + 1);
    					wordBegin += wordLength;
    					wordLength = 0;
    				}
    			}
    		}
    		s.resize(wordBegin - s.begin());
    		std::reverse(s.begin(), s.end());
    	}
    };
    

    After the for loop, all extra space chars are swapped to the end of the string s.

    I do really hoping for some help to make my code run within 8 ms! Any advice?


Log in to reply
 

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