For this program, why I input " a b " and output "a b", but in my visual stadio the output is "b a"@_@


  • 0
    S
    class Solution {
    public:
        void output(string s, int f, int l)
    	{
    		for (int i = f; i <= l; i++)
    		{
    			cout << s[i];
    		}
    	}
    
        void reverseWords(string &s){  
            for (int i = 0; i < s.size(); i++)
    		{
    			if (i == 0 && s[i] == ' ')
    			{
    				string::iterator iter = s.begin();
    				iter = s.erase(iter);
    				i--;
    				continue;
    			}
    			if (i == s.size() - 1 && s.back() == ' ')
    			{
    				string::iterator iter = s.begin() + i;
    				iter = s.erase(iter);
    				i--;
    				continue;
    			}
    			if (s[i] == ' ' && s[i + 1] == ' ')
    			{
    				string::iterator iter = s.begin() + i + 1;
    				iter = s.erase(iter);
    				i--;
    				continue;
    			}
    		}
    
    		if (s.size() > 0)
    		{
    			int last = s.size() - 1, first;
    			for (int i = s.size() - 1; i >= 0; i--)
    			{
    				if (i == 0)
    				{
    					first = i;
    					output(s, first, last);
    				}
    				if (s[i] ==  ' ')
    				{
    					first = i + 1;
    					output(s, first, last);
    					cout << " ";
    					last = i - 1;
    				}
    			}
    		}
        }
    };

  • 1
    R

    i got the same error initially, open the string in vs you'll see 2 spaces b/w a and b.


  • 0
    S

    I check again and again, but there is one space between a and b, and their order are right. Can you explain clearly about your condition and how to deal with? thx.


  • 0
    S

    I have solved my problem.In fact, the problem request me to change the argument 's' to the result string,but I mistake as outputing the result.^_^


Log in to reply
 

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