leetcode每日一题--逆波兰表达式求值

https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

逆波兰表达式也就是后缀表达式,直接通过栈即可求出答案。

难的不是逆波兰表达式的求值,难的是将中缀表达式转化为后缀表达式。

 1 class Solution {
 2 public:
 3     stack<int> stk;
 4     void cal(string x){
 5         int a=stk.top();stk.pop();
 6         int b=stk.top();stk.pop();
 7         if(x=="+")
 8             stk.push(a+b);
 9         else if(x=="-")
10             stk.push(b-a);
11         else if(x=="*")
12             stk.push(a*b);
13         else if(x=="/")
14             stk.push(b/a);
15     }
16     int evalRPN(vector<string>& tokens) {
17         unordered_set<string> S={"+","-","*","/"};
18         for(auto &x:tokens){
19             if(S.count(x)){
20                 cal(x);
21             }else{
22                 stk.push(stoi(x));
23             }
24         }
25         return stk.top();
26     }
27 };
原文地址:https://www.cnblogs.com/greenofyu/p/14569389.html