Why I got WRONG ANSWER since Output is same as Expected


  • 0
    W
    class Solution {
    public:
        void reverseWords(string &s) { 
            int word_start = 0, word_end = 0, str_len = s.size(), index = 0;
            reverse_self(s, 0, str_len - 1);
            for(int i = 0; i < str_len; i++)
            {
                if(s[i] != ' ')
                {
                    word_start = i;
                    word_end = i;
                    int j = i;
                    for(; j < str_len; j++)
                    {
                        if(s[j] != ' ')
                            word_end++;
                        else
                            break;
                    }
                    reverse_self(s, word_start, word_end-1);
                    i = j + 1;
                    while(word_start <= word_end)
                    {
                        s[index++] = s[word_start++];
                    }
                    if(index < str_len)
                        s[index++] = ' ';
                }
            }
            if(s[index-1] == ' ')
                s.resize(--index);
            if(index == 0)
                s.resize(index);
        }
    private:
        void reverse_self(string &s, int start, int end) {
            if(start < end)
                swap(s[start++], s[end--]);
        }
    };
    

    The test case:


    Input: "1 "


    Output: "1"


    Expected: "1"


  • 0
    D

    If compile and execute your code, you will receive the size of output string equals 2

    int main() {
        string val("1 ");
        Solution().reverseWords(val);
        cout << val.size() << endl;
    }
    

    This is because of std::string implementation. It consists of given string and 0-termination. In our case the string data is "1 \0" after you algorithm the result is: "1\0 " and this gives output: "1", but it's not equals to reference value (string with size 1, not 2)


Log in to reply
 

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