/** * @param expression: a vector of strings; * @return: an integer */ int evaluateExpression(vector<string> &expression) { // write your code here if(expression.size() == 0){ return 0; } // 1. converted to reversed polish expression vector<string> rpe = convertToRPN(expression); // 2. caculate the reversed polish expression return calculateRPN(rpe); }
int evalRPN(vector<string> &tokens) { stack<int> s; for (vector<string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { //如果是数字 if (isNumber(*it)) s.push(stoi(*it)); //将数字压入栈中 //如果是运算符 else if (*it == "+" || *it == "-" || *it == "*" || *it == "/") { if (!s.empty()) { //如果栈中有数字 int opnd2 = s.top(); //获得表达式中的右边的操作数 s.pop(); //弹出 int opnd1 = s.top(); //获得左边的操作数 s.pop(); //弹出 s.push(calculate(opnd1, it->c_str(), opnd2)); //计算表达式,将结果再压入栈中 } } //如果是表达式 else { vector<string> anotherTokens; s.push(evalRPN(anotherTokens = convertToRPN(*it))); //如果是表达式那么转化成逆波兰式,在调用evalRPN,所得结果压入栈中 } } return s.top(); //返回最终结果 }
/** * @param expression: A string array * @return: The root of expression tree */ ExpressionTreeNode* build(vector<string> &expression) { // write your code here vector<string> rpn = convertToRPN(expression); stack<ExpressionTreeNode*> stk; for(auto e : rpn){ if(e == "+" || e == "-" || e == "*" || e == "/"){ ExpressionTreeNode* r = stk.top(); stk.pop(); ExpressionTreeNode* l = stk.top(); stk.pop(); ExpressionTreeNode* node = new ExpressionTreeNode(e); node->left = l; node->right = r; stk.push(node); }else{ ExpressionTreeNode* node = new ExpressionTreeNode(e); stk.push(node); } } if(stk.size()) return stk.top(); else return NULL; }