Evaluate Reverse Polish Notation

题目来源
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

计算逆波兰表达式的值,这个感觉比较简单,就是利用一个栈,把数字都进栈,然后碰到一个符号就出栈两个数字,把结果进栈,直到表达式结束或栈空。
就是这么简陋的写法,不过至少能AC是不

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int n = tokens.size();
        stack<int> s;
        for (int i=0; i<n; i++) {
            if (tokens[i] == "+") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x1 + x2);
            }
            else if (tokens[i] == "-") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x2 - x1);
            }
            else if (tokens[i] == "*") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x1 * x2);
            }
            else if (tokens[i] == "/") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x2 / x1);
            }
            else {
                int x = stoi(tokens[i]);
                s.push(x);
            }
        }
        return s.top();
    }
};

有点长,写的简洁一点…

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int n = tokens.size();
        stack<int> s;
        for (int i=0; i<n; i++) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                if (tokens[i] == "+")
                    s.push(x1 + x2);
                else if (tokens[i] == "-")
                    s.push(x2 - x1);
                else if (tokens[i] == "*")
                    s.push(x1 * x2);
                else
                    s.push(x2 / x1);
            }
            else {
                int x = stoi(tokens[i]);
                s.push(x);
            }
        }
        return s.top();
    }
};

不过写简洁了,时间变长了一些,不过其实复杂度是一样的是不。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容