Lintcode 逆波兰表达式求值

来源:互联网 发布:windows画图软件 编辑:程序博客网 时间:2024/05/17 08:14

求逆波兰表达式的值。

在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

您在真实的面试中是否遇到过这个题? Yes
样例
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

简单的退栈和入栈的问题,重点是要搞清逆波兰表达式的含义

class Solution {public:    /*     * @param tokens: The Reverse Polish Notation     * @return: the value     */    int string_to_int(const string &string1) {        int sym = 1;        int num = 0;        for (auto i : string1) {            if (i == '-') {                sym = 0;                continue;            }            num = num * 10 + (i - '0');        }        return sym == 0 ? -num : num;    }    int evalRPN(vector<string> tokens) {        // write your code here        stack<int> stack1;        int temp = 0;        int after = 0;        for (auto s :tokens) {            if (s == "+" || s == "-" || s == "*" || s == "/") {                if (s == "+") {                    temp = after + stack1.top();                } else if (s == "-") {                    temp = after - stack1.top();                } else if (s == "*") {                    temp = after * stack1.top();                } else if (s == "/") {                    temp = after / stack1.top();                }                stack1.pop();                stack1.pop();                if (!stack1.empty()) {                    after = stack1.top();                }                stack1.push(temp);            } else {                if (!stack1.empty()) {                    after = stack1.top();                }                stack1.push(string_to_int(s));            }        }        return stack1.top();    }};