某势科技笔试题
输入一个串"PUSH -100;POP 1;PUSH -10;PUSH 20;PUSH 30;POP 2",输出模拟栈的结果。PUSH XX表示把XX压栈,POP XX表示从栈中弹出XX个数。输出结果。
#include <bits/stdc++.h>
using namespace std;
const string PUSH = "PUSH";
const string POP = "POP";
vector<string> stringSplit(string& str, const char split)
{
vector<string> res;
istringstream iss(str);
string token;
while (getline(iss, token, split))
{
res.push_back(token);
}
return res;
}
vector<int> interpreStatement(string& statement)
{
vector<int> res;
stack<int> stk;
vector<string> state_arr = stringSplit(statement, ';');
for (auto&& elem : state_arr)
{
vector<string> state_arr_kv = stringSplit(elem, ' ');
if (state_arr_kv.at(0) == PUSH)
{
stk.push(atoi(state_arr_kv.at(1).c_str()));
}
else if (state_arr_kv.at(0) == POP)
{
for (int i = 0; i < atoi(state_arr_kv.at(1).c_str()); i++)
{
if (stk.empty())
{
break;
}
stk.pop();
}
}
}
while (!stk.empty())
{
res.push_back(stk.top());
stk.pop();
}
return res;
}
int main()
{
string oper_statement;
getline(cin, oper_statement);
vector<int> oper_vec = interpreStatement(oper_statement);
for (auto&& elem : oper_vec)
{
cout << elem << " ";
}
cout << endl;
return 0;
}