Test case 4 of "Reverse words in a string"


  • 0
    S

    For test case 4,

    class Solution {
    public:
    /**
    * @param s : A string
    * @return : A string
    */
    string reverseWords(string s) {
    // write your code here
    if (s.empty())
    {
    return s;
    }

    string result;
    
    int size = int(s.size());
    int i;
    int start = 0;
    int end;
    
    for (i = 0; i < size; i++)
    {
    	if ((i == 0 || s[i - 1] == ' ') && s[i] != ' ')
    	{
    		start = i;
    		if (start != 0)
    		{
    			result.push_back(' ');
    		}
    	}
    	if (s[i] != ' ' && (i == size - 1 || s[i + 1] == ' '))
    	{
    		end = i;
    		reverse(s, start, end);
    	
    		for (int j = start; j <= end; j++)
    		{
    			result.push_back(s[j]);
    		}
    	}
    }
    reverse(result, 0, int(result.size()) - 1);
    return result;
    	
    }
    

    void reverse(string &s, int start, int end)
    {
    int temp, i, j;
    for (i = start, j = end; i < j; i++, j--)
    {
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
    }
    }
    };

    Input: “ ”
    Output: " "
    Expected: “”

    I do think my code can handle case 4 and it works on both Visual c++ and another online judge system which also has this problem. But it will always fail at test case 4 here.

    Is there anyone knowing why?


Log in to reply
 

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