题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
使用栈
class Solution {
public:
string ReverseSentence(string str) {
vector<char> ue;
stack<char>bp;
string res;
int str_size = str.size();
int count_k = 0;
for (int i = 0;i < str_size;i++)
{
ue.push_back(str[i]);
if (str[i] == ' ')count_k++;
}
if (count_k!=0)
{
for (int i = str_size - 1;i >= 0;--i)
{
if (ue.back() == ' ')
{
while (!bp.empty())
{
res += bp.top();
bp.pop();
}
res += ' ';
ue.pop_back();
continue;
}
if (i == 0)
{
bp.push(ue.back());
while (!bp.empty())
{
res += bp.top();
bp.pop();
}
break;
}
bp.push(ue.back());
ue.pop_back();
}
}
else
{
for (int i = str_size - 1;i >= 0;i--)
{
bp.push(ue.back());
ue.pop_back();
}
for (int i = str_size - 1;i >= 0;i--)
{
res += bp.top();
bp.pop();
}
}
return res;
}
};