题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param tokens string字符串一维数组
# @return int整型
#
# 逆波兰表达式,基本思路,将列表进栈,如果遇到运算符号,出栈两个元素,得到一个结果,将这个结果入栈
# 然后如果再遇到运算符号再进行运算。
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        # write code here
        stack = []
        op = "+-*/"
        print(tokens)
        for i in tokens:
            if i not in op:
                stack.append(i)
            elif i in op:
                a = int(stack.pop())
                b = int(stack.pop())
                if i == "+":
                    stack.append(str(a+b))
                elif i == "-":
                    stack.append(str(b-a))
                elif i == "*":
                    stack.append(str(a*b))
                elif i == '/':
                    stack.append(str(int(b/a)))
        return int(stack[0])

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务