What is the mistake in my code?


  • 0
    S
    class Solution {
    public:
        void reverseWords(string &s) {
            
        int i=0,j=s.length()-1,k=0,l;
        char t;
        
        //reverse the string
        while(i<j)
        {
                t=s[i];
                s[i]=s[j];
                s[j]=t;
    
                i++;j--;
        }
        
        //trim extra whitespaces
        i=0;j=0;
        while(s[j]!='\0')
        {
            if(s[j]!=' ')
            {
                s[i]=s[j];
                i++;j++;
            }
            
            else
            {
                if(i!=0)
                i++;
                
                j++;
                
                while(s[j]==' ' && s[j]!='\0')
                j++;
            }
        }
        s[i]='\0';
        
        if(s.length()==0)
        return;
        
        //reverse each word one by one
        i=0;j=0;k=0;
        while(s[k]!='\0')
        {
            while(s[k]!=' ' && s[k]!='\0')
            {
                k++;
            }
            
            j=k-1;
            
            while(i<j)
            {
                t=s[i];
                s[i]=s[j];
                s[j]=t;
    
                i++;j--;
            }
            
            if(s[k]!='\0')
            k++;
            
            i=k;
        }
        
     }
    };
    

    I am getting WRONG ANSWER for the case " ". However the output from my code is the same as the output provided by OJ.

    Here is the message I am getting.

    13 / 22 test cases passed.
    Status: Wrong Answer
    Submitted: 0 minutes ago
    Input: " "
    Output: ""
    Expected: ""


Log in to reply
 

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