Reputation: 2419
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;
}
Upvotes: 0
Views: 570
Reputation: 5369
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
Upvotes: 1