LeetCode——Evaluate Reverse Polish Notation

来源:互联网 发布:linux检查文件是否存在 编辑:程序博客网 时间:2024/05/29 14:56

题目:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are +, -, *, /. Each operand may be an integer or another expression.Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

解答:

class Solution {public:    int calcWithOperator(const string& op, int l, int r) {        char c = *op.c_str();        switch (c) {            case '+':                return l + r;            case '-':                return l - r;            case '*':                return l * r;            case '/':                return l / r;        }        return 0;    }    bool isStringOperator(const string& str) {        if (str.length() != 1) {            return false;        }        char c = *str.c_str();        return c == '+' || c == '-' || c == '*' || c == '/';    }    int evalRPN(vector<string>& tokens) {        stack<int> stackNum;        for (int i = 0; i != tokens.size(); ++i) {            const string str = tokens[i];            if (isStringOperator(str)) {                if (stackNum.size() < 2) {                    return -1;                } else {                    int r = stackNum.top();                    stackNum.pop();                    int l = stackNum.top();                    stackNum.pop();                    int result = calcWithOperator(str, l, r);                    stackNum.push(result);                }            } else {                stackNum.push(atoi(str.c_str()));            }        }        if (stackNum.size() != 1) {            return -1;        } else {            return stackNum.top();        }    }};
0 0
原创粉丝点击