简体   繁体   English

反转字符串中的单词,

[英]Reverse words in a string,

Leetcode question: Given an input string, reverse the string word by word. Leetcode问题:给定输入字符串,逐个单词地反转字符串。

For example, Given s = "the sky is blue", return "blue is sky the". 例如,给定s =“天空是蓝色”,则返回“蓝色是天空”。

Can anyone explain why leetcode always give me error sign about : Input : " " Output: " " Expected: "" 任何人都可以解释为什么leetcode总是给我有关以下错误符号的信息:输入:“”输出:“”预期:“”

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 预期输出: "" -空字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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