cpp solution using stack


  • 0
    H
    class Solution {
    public:
    	void reverseWords(string &s) {
    		stack<string> ss;
    		string str = "";
    		for (int i = 0; i < s.size(); i++)
    		{
    			if (s[i] == ' ')
    			{
    				if (str.size() == 0)
    					continue;
    				ss.push(str);
    				str = "";
    			}
    			else
    				str += s[i];
    		}
    		if (str.size() != 0)
    			ss.push(str);
    		s = "";
    		int i = ss.size();
    		while (i > 0)
    		{
    			s += ss.top();
    			ss.pop();
    			i--;
    			if (i)
    				s += ' ';
    		}
    	}
    };
    

Log in to reply
 

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