【leetcode刷题】T20-逆波兰表达式求值

2019-07-17 10:06:24 浏览数 (1)

代码语言:javascript复制
今天分享leetcode第20篇文章,也是leetcode第150题—逆波兰表达式求值(Evaluate Reverse Polish Notation),地址是:https://leetcode.com/problems/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.Note:Division between two integers should truncate toward zero.The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.Example 1:Input: ["2", "1", " ", "3", "*"]
Output: 9
Explanation: ((2   1) * 3) = 9
Example 2:Input: ["4", "13", "5", "/", " "]
Output: 6
Explanation: (4   (13 / 5)) = 6
【中文题目】根据逆波兰表示法,求表达式的值。有效的运算符包括  , -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。说明:整数除法只保留整数部分。给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。示例 1:输入: ["2", "1", " ", "3", "*"]
输出: 9
解释: ((2   1) * 3) = 9
示例 2:输入: ["4", "13", "5", "/", " "]
输出: 6
解释: (4   (13 / 5)) = 6
【思路】逆波兰表示法,也称为后缀表示法,即将运算符写在操作数之后。比如:3 5的逆波兰表示法为["3", "5", " "],(3 5) * 2的逆波兰表示法为["3", "5", " ", "2", "*"]。逆波兰式在计算机看来是比较简单易懂的结构,因为计算机普遍采用的内存结构是栈式结构。这是使用栈的典型题,遇到数字添加元素,遇到操作符弹出元素进行相应操作即可。有一点需要注意的是:c  对于两个整数相除结果,正数向下取整,负数向上取整;而python都是向下取整。本题取整需要按照c  取整方式。【代码】python版本class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        op = set(' -*/')
        ls = []
        for t in tokens:
            # 是符号
            if t in op:
                b = ls.pop()
                a = ls.pop()
                if t == ' ':
                    ls.append(a   b)
                elif t == '-':
                    ls.append(a - b)
                elif t == '*':
                    ls.append(a * b)
                else:
                    # python和C  对整数相除取整的不同之处
                    # c  :正数向下取整,负数向上取整
                    res = abs(a) / abs(b)
                    if a * b < 0:
                        res *= -1
                    ls.append(res)
                print(ls[-1])
            # 是数字
            else:
                ls.append(int(t))
        return ls[0]
C  版本class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> num;
        set<string> op = {" ", "-", "*", "/"};
        int a, b;
        for(int i=0; i < tokens.size(); i  ){
            string t = tokens[i];
            if(op.find(t) != op.end()){
                b = num.top();
                num.pop();
                a = num.top();
                num.pop();
                if(t == " ")
                    num.push(a   b);
                if(t == "-")
                    num.push(a - b);
                if(t == "*")
                    num.push(a * b);
                if(t == "/")
                    num.push(a / b);
            }else
                num.push(atoi(t.c_str()));
        }
        return num.top();
    }
};

0 人点赞