Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- using namespace std;
- #include <iostream>
- #include <string>
- #include <vector>
- #include <sstream>
- #include <cctype>
- #include <stack>
- int solution(string &S) {
- stringstream ss(S);
- vector<string> commands;
- string command;
- while (getline(ss,command,' ')) {
- commands.push_back(command);
- }
- stack<int> st;
- for (auto i : commands) {
- if (isdigit(i[0])) {
- st.push(stoi(i));
- } else if (isalpha(i[0])) {
- if (i[0] == 'P') {
- st.pop();
- } else if (i[0]=='D') {
- st.push(st.top());
- }
- } else {
- if (st.size() < 2) {
- cout << i;
- return -1;
- } else {
- int first = st.top();
- st.pop();
- int second = st.top();
- st.pop();
- if (i[0] == '+') {
- st.push(first+second);
- } else if (i[0] == '-') {
- int diff = second - first;
- if (diff < 0) {
- cout << i;
- return -1;
- } else {
- st.push(diff);
- }
- }
- }
- }
- }
- return st.top();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement