题解 | 表达式求值

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

"""
https://blog.nowcoder.net/n/c8c1ff4ecfb44ca4958b1ecbdcbf2021
#print(ss.solve("(2*(3-4))*5"))  # -10
#print(ss.solve("(22*(3-4))*5"))  # 有多位数
#print(ss.solve("-5+10*2"))  # 第一个数为负数
print(ss.solve("(3+4)*(5+(2-3))"))  # 28

"""


import collections

class Solution:
    def calc(self,nums: collections.deque, ops: collections.deque):
        if len(nums) == 0 or len(nums) < 2:
            return
        if len(ops) == 0:
            return
        b = nums.pop()
        a = nums.pop()
        op = ops.pop()
        ans = 0
        if op == '+':
            ans = a + b
        elif op == '-':
            ans = a - b
        elif op == '*':
            ans = a * b
        nums.append(ans)
    def solve(self, s: str) -> int:
        map = dict()
        # 加减的优先级一样 ,乘的优先级为2
        map['+'] = 1
        map['-'] = 1
        map['*'] = 2
        # 将所有空格去掉
        s = s.replace(" ", "")
        n = len(s)
        # 存入所有数字
        nums = collections.deque()
        # 为了防止第一个数为负数 ,将0添加到队列
        nums.append(0)
        # 队列二 存入所有非数字
        ops = collections.deque()
        # 遍历字符
        #  字符为为“)”
        #for i in range(n):  # 多个数字会有问题
        i = 0
        while i < n:
            ch = s[i]
            if ch == '(':  #左括号
                ops.append(ch)
            elif ch == ')':  # 右括号
                # 计算到最后一个括号为止
                # 操作不为空/c
                while ops:
                    if ops[-1] != '(':
                        self.calc(nums, ops)

                    else:
                        ops.pop()
                        break# 弹出对应的左括号
            else:
                if ch.isdigit():
                    u = 0
                    j = i
                    # 将连续数字拼接
                    # 将 (- 替换为(0-
                    # (+ 替换为(0+
                    while j < n and s[j].isdigit():
                        u = u * 10 + int(s[j])
                        j = j + 1
                    i = j - 1
                    # 数字添加到nums
                    nums.append(u)
                else:  # 加减处理
                    if i > 0 and (s[i - 1] == '(' or s[i - 1] == '+' or s[i - 1] == '-'):
                        nums.append(0)

                    # 有一个新操作时候将栈内的可以计算的计算掉
                    # 只有满足【栈内运算符】比【当前运算符】优先计算
                    while len(ops) > 0 and ops[-1] != '(':
                        prev = ops[-1]
                        if map[prev] >= map[ch]:
                            self.calc(nums, ops)
                        else:
                            break
                    ops.append(ch)
            i += 1  # 指向下一个位置
        while len(ops) > 0 and ops[-1] != '(':
            self.calc(nums, ops)
        return nums[-1]

全部评论

相关推荐

07-18 14:55
门头沟学院 Java
点赞 评论 收藏
分享
炫哥_:为什么都读硕士了?项目还是网上的项目(真心发问)
最后再改一次简历
点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
07-15 11:43
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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