您的位置:首页 > 编程语言 > Lua

LeetCode(150) Evaluate Reverse Polish Notation

2014-12-24 17:51 225 查看
题目如下:

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

分析如下:

使用stack的基础型题目。

我的代码:

//80ms
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        int i = 0;
        int operand1 = 0;
        int operand2 = 0;
        stack<int> operand_stack;
        while (i < tokens.size()) {
            if (tokens[i] == "+") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 + operand1);
            } else if (tokens[i] =="-") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 - operand1);
            } else if(tokens[i] == "*") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 * operand1);
            } else if (tokens[i] == "/") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 / operand1);
            } else {
                operand1 = atoi(tokens[i].c_str());
                operand_stack.push(operand1);
            }
            i++;
        }
        return operand_stack.top();
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: