我的方法很笨,就是用空间换时间,先把每个单词存下来,在倒着拼起来
明明在VS上运行的好好的,牛客上非说
格式错误:您的程序输出的格式不符合要求(比如空格和换行与要求不一致)
class Solution {
public:
string ReverseSentence(string str) {
string res;
int n = str.size();
if (n == 0 || n == 1)
return res;
vector<string> words;
int word_begin = 0;
for (int i = 0; i<n; i++)
{
char c = str[i];
if (i == n - 1)
{
string temp(str, word_begin, i - word_begin+1);
words.push_back(temp);
}
if(c==' ')
{
string temp(str, word_begin, i - word_begin);
words.push_back(temp);
word_begin = i + 1;
}
}
for (int i = words.size()-1; i >=0; i--)
{
if (i == 0)
res += words[i];
else {
res += words[i];
res += ' ';
}
}
return res;
}
};