题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
#include <algorithm>
#include <string>
class Solution {
public:
string ReverseSentence(string str)
{
if (str.empty())
{
return "";
}
int index = str.find_first_of(' ');
int find_index = 0;
stack<string> s;
while (index > 0)
{
string tmp = str.substr(find_index, index - find_index);
s.push(tmp);
find_index = index + 1;
index = str.find_first_of(' ', find_index);
}
//最后一个单词
string tmp = str.substr(find_index,str.length());
s.push(tmp);
string str_res;
while (!s.empty())
{
str_res += s.top() + ' ';
s.pop();
}
//去掉最后面的空格
str_res = str_res.substr(0, str_res.length() - 1);
return str_res;
}
};
查看6道真题和解析