leetcode 150. Evaluate Reverse Polish Notation
Posted ymjyqsx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 150. Evaluate Reverse Polish Notation相关的知识,希望对你有一定的参考价值。
https://www.cnblogs.com/grandyang/p/4247718.html
逆波兰表达式就是把操作数放前面,把操作符后置的一种写法。用stack解决就好了。
class Solution { public: int evalRPN(vector<string>& tokens) { if(tokens.empty()) return 0; stack<int> s; for(int i = 0;i < tokens.size();i++){ if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") s.push(stoi(tokens[i])); else{ int num1 = s.top(); s.pop(); int num2 = s.top(); s.pop(); int tmp; if(tokens[i] == "+") tmp = num1 + num2; else if(tokens[i] == "-") tmp = num2 - num1; else if(tokens[i] == "*") tmp = num1 * num2; else if(tokens[i] == "/") tmp = num2 / num1; s.push(tmp); } } return s.top(); } };
以上是关于leetcode 150. Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode150. Evaluate Reverse Polish Notation
刷题-LeetCode150 Evaluate Reverse Polish Notation
[LeetCode] 150. Evaluate Reverse Polish Notation
[LeetCode] 150. Evaluate Reverse Polish Notation