Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include <algorithm>
  2. using namespace std;
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <sstream>
  7. #include <cctype>
  8. #include <stack>
  9.  
  10. int solution(string &S) {
  11. stringstream ss(S);
  12.  
  13. vector<string> commands;
  14. string command;
  15.  
  16. while (getline(ss,command,' ')) {
  17. commands.push_back(command);
  18. }
  19.  
  20. stack<int> st;
  21.  
  22. for (auto i : commands) {
  23. if (isdigit(i[0])) {
  24. st.push(stoi(i));
  25. } else if (isalpha(i[0])) {
  26. if (i[0] == 'P') {
  27. st.pop();
  28. } else if (i[0]=='D') {
  29. st.push(st.top());
  30. }
  31. } else {
  32. if (st.size() < 2) {
  33. cout << i;
  34. return -1;
  35. } else {
  36. int first = st.top();
  37. st.pop();
  38. int second = st.top();
  39. st.pop();
  40.  
  41. if (i[0] == '+') {
  42. st.push(first+second);
  43. } else if (i[0] == '-') {
  44. int diff = second - first;
  45. if (diff < 0) {
  46. cout << i;
  47. return -1;
  48. } else {
  49. st.push(diff);
  50. }
  51. }
  52. }
  53. }
  54. }
  55.  
  56. return st.top();
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement