Evaluate Reverse Polish Notation, evaluatenotation
Original question link: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
Question: Give the inverse Polish style and then ask for the result.
Solution: Single stack
Idea: traverse the inverse Polish formula. If it is a number, it is written into the stack. If it is an operator, two elements at the top of the stack will pop up, and then the result of the corresponding operator will be written into the stack. After the traversal is complete, the elements in the stack are the desired results.
Time Complexity: O (N) space complexity: O (1)
class Solution {public: int evalRPN(vector<string> &tokens) { if(tokens.empty()) return 0; stack<int> s; int op1=0,op2=0; for(int i=0;i<tokens.size();i++) { if(tokens[i]=="+") { op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1+op2); } else if(tokens[i]=="-") { op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1-op2); } else if(tokens[i]=="*") { op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1*op2); } else if(tokens[i]=="/") { op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1/op2); } else s.push(atoi(tokens[i].c_str())); } return s.top(); }};