Reverse Words in a String in c++【output is the same with expected,but OJ shows "wrong answer", why?】


  • 0
    X

    class Solution {
    public:
    void reverseWords(string &s) {

        if(s.empty())return;
        s.erase(0,s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ")+1);
        
        for(int i=0;i<s.length()/2;i++)
        {
            char c=s[i];
            s[i]=s[s.length()-i-1];
            s[s.length()-i-1]=c;
        }
        
        for(int i=0;i<s.length();i++)
        {
            if(s[i]!=' ')
            {
                int start=i;
                while(i<s.length() && s[i]!=' ')i++;
                
                for(int j=start;j<start+(i-start)/2;j++)
                {
                    char c=s[j];
                    s[j]=s[i-j-1];
                    s[i-j-1]=c;
                }
            }
        }
    }
    

    };


Log in to reply
 

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