NC137 表达式求值

遇到这种使用栈来做计算,就有些迷糊,这是看了答案来理解的。

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 返回表达式的值
# @param s string字符串 待计算的表达式
# @return int整型
#
class Solution:
    def solve(self , s: str) -> int:
        # write code here
        #使用递归和栈
        s = s.strip()#去除空格
        stack = []
        num = 0
        index = 0
        sign = '+'
        res = 0
        while index < len(s):
            if s[index]==' ':
                index += 1
                continue

            #遇到左括号,进入递归
            if s[index] == '(':
                end = index + 1
                lens = 1
                while lens > 0:
                    if s[end] == '(':
                        lens += 1
                    if s[end] == ')':
                        lens -= 1
                    end += 1
                #将本层级括号的内容视为子问题进入递归
                num = self.solve(s[index+1 : end-1])
                index = end - 1#?
                continue

            #字符数字转换成int格式,核心步骤
            if '0' <= s[index] <='9':
                num = num*10 + int(s[index])#多位数的情况
            #根据符号进行计算
            if not '0'<=s[index]<='9' or index==len(s)-1:
                if sign == '+':
                    stack.append(num)
                elif sign == '-':
                    stack.append(-1*num)
                elif sign == '*':
                    stack.append(stack.pop()*num)
                num = 0
                sign = s[index]
            index += 1
        while stack:
            res += stack.pop()
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值