简体   繁体   中英

Reverse words in a string,

Leetcode question: Given an input string, reverse the string word by word.

For example, Given s = "the sky is blue", return "blue is sky the".

Can anyone explain why leetcode always give me error sign about : Input : " " Output: " " Expected: ""

As I test locally, it outputs just expected. Weird.

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <stdlib.h>
#include <string>

using namespace std;

class Solution{
    public:
        static string reverseWords(string &s)
        {
            vector<string> words;
            string word = "";
            //get each word
            for(int i = 0 ; i <= s.size(); i++)
            {               
                if(s[i] == ' ' || i == s.size())
                {
                    if(word!="")
                    {
                        words.push_back(word);
                        word = "";
                    }
                }
                else
                {
                    word += s[i];
                }
            }

            // for (vector<string>::iterator i = words.begin(); i!=words.end(); i++) {
            //     cout<<*i<<endl;
            // }

            string reverseStr = "";
            //pop reverse order 
            int size = words.size();
            for(int i = 0; i < size ; i++)
            {
                if(i != size-1)
                {
                    reverseStr +=  words.back() + ' ';

                }
                else{
                    reverseStr += words.back();
                }
                words.pop_back();
            }

            return reverseStr;
        }
};

int main(int argc, char const *argv[])
{
    string s = " the sky is   blue ";
    Solution::reverseWords(s);

    return 0;
}

When there are no words in the string, the output will be an empty string. That is, the output string will be "" . It should not contain a space.

Input : " " - a space

Expected output : "" - empty string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM