My code works but OJ says it's wrong.


  • 0
    T

    I've submitted my answer as following:

    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            splitted = s.split(' ')
            splitted.reverse()
            return ' '.join([x for x in splitted])
    

    And according to the Python console, it works fine yet LeetCode OJ says my answer is wrong. Any inputs? Or is this simply a bug in their software?


  • 0
    A

    this is my code, maybe it's helpful to you, I wonder why the ac rate is so low for this problem..

    class Solution {
    public:
        void reverseWords(string &s) {
            istringstream iss(s);
    
            vector<string> word_list;
            string word;
            
            while (iss >> word){
                word_list.push_back(word);
            }
            
            ostringstream oss;
            if (word_list.size() > 0)
                oss << word_list[word_list.size()-1];
            
            for (int i = word_list.size() - 2 ; i >= 0; --i)
                oss << " " << word_list[i];
                
            s = oss.str();
        }
    };

  • 0
    S

    Maybe they are trying to get rid of stringstream, not quite sure such solution would be accepted in a real interview. If I were an interviewee, I might also need a pure string manipulation solution.


  • 0
    J

    you can replace ' ' with '_' so that you can find the error.


  • 0
    T

    I am quite new to Python. Would you please kindly explain the difference between the two? Thank you :)


  • 1
    M
    class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        tmplist = s.split(' ')
        tmplist.reverse()
        return ' '.join([x for x in tmplist if x])
    

    accept.


  • 0
    T

    Thanks! So I was missing the 'if x' part!


Log in to reply
 

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