[LeetCode]Evaluate Reverse Polish Notation

来源:互联网 发布:淘宝打折活动名称 编辑:程序博客网 时间:2024/05/16 14:57

这道题主要难点是栈(stack)的使用。

#include <iostream>#include <string.h>#include <vector>#include <stack>using namespace std;class Solution {public:bool IsOp(string s){if (s == "+" || s == "-" || s == "*" || s == "/")return true;else return false;}int evalRPN(vector<string> &tokens) {vector<string>::iterator it;stack<int> s;int result = 0;for (it = tokens.begin(); it != tokens.end(); it++){int a;if (!IsOp(*it)){a = atoi((*it).data());s.push(a);}else{char op = (*it).data()[0];int a = s.top(); s.pop();int b = s.top(); s.pop();switch (op){case '+':result = b + a; break;case '-':result = b - a; break;case '*':result = b * a; break;case '/':result = b / a; break;default:break;}s.push(result);}}return s.top();}};


0 0