leetcode 127. Word Ladder

题目

在这里插入图片描述

解法:stack

题目跟calculator很相似,用stack即可解决
有两个注意点:

  1. python的isdigit函数对于负数情况需要单独判断
  2. 这边的负数出发也要注意,//操作是向下取整,int是直接去掉小数部分
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for op in tokens:
            # isdigit function does not work for negative number
            if op.isdigit() or op[1:].isdigit():
                # print(op)
                stack.append(int(op))
            else:
                second_num = stack.pop()
                first_num = stack.pop()
                if op == '+':
                    stack.append(first_num+second_num)
                elif op == '-':
                    stack.append(first_num-second_num)
                elif op == '*':
                    stack.append(first_num*second_num)
                elif op == '/':
                    # need to do division first and convert to int, // will do rounds down
                    # for example -1//2 = -1 rather than 0
                    # int operation cuts the float part and remain the int part
                    stack.append(int(first_num / second_num))
        # print(stack)
        return stack[0]

时间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值