How to address the annoying Input:" " Output:" " Expected: "" error?


  • 0
    B
    class Solution {
    public:string reverseWords(string &s) {
        const char* str = s.c_str();
        char* p;
        vector<string> components;
        string result="";
        
        p = strtok((char*)str, " ");
        
        if(p == NULL) return result;
        
        while(p != NULL){
            components.push_back(p);
            p = strtok(NULL, " ");
        }
        
        int size = components.size();
        
        for(int i = size - 1; i > 0; i--)
            result = result + components[i] + " ";
        
        result += components[0];    
        
        return result;
        
        }
    };
    

    The above is my code, I am encountered with the following annoying error:

    Submission Result: Wrong Answer

    Input: " "

    Output: " "

    Expected:""

    Actually my program really returns "" when the input is " ", rather than " ". Please give me a hand to address this error. You help are very much appreciated!


  • 1
    G

    first,you should delete the spaces at the begin or at the end of the string,
    and then you should erase the redundant spaces in the string.
    for an example a string like "\040\040aa\040\040bb\040cc\040\040"
    convert to "aa\040bb\040cc"
    "\040" -> ""
    \040 means space
    this is the way i solve the problem and I hope it may help you


  • 0
    B

    If you have read my code, you would find that I convert the C++ string into c style string, and then invoke strtok(), which helps to remove all the redundant spaces...


Log in to reply
 

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