题解 | #表达式求值#

表达式求值

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

"表达式求值”问题,两个核心关键点:

  1. 双栈,一个操作数栈,一个运算符栈;
  2. 运算符优先级,栈顶运算符,和,即将入栈的运算符的优先级比较:
  3. 如果栈顶的运算符优先级低,新运算符直接入栈
  4. 如果栈顶的运算符优先级高,先出栈计算,新运算符再入栈

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 返回表达式的值
# @param s string字符串 待计算的表达式
# @return int整型
#

level = {"+": 1, "-": 1, "*": 2, "/": 2, "(": 3, ")": -1}

#中缀表达式求值
class Solution:
    def solve(self , s: str) -> int:
        # write code here
        s = s + ')'

        n = len(s)
        i = 0

        opt = []
        opt.append('(')
        num = []

        while i < n:
            t = i
            while s[t].isdigit():
                t += 1
            if(t != i):
                num.append(int(s[i:t]))
                i = t
                continue

            if opt[-1] == '(' and s[i] != ')':
                opt.append(s[i])
                i += 1
            elif level[s[i]] > level[opt[-1]]:
                opt.append(s[i])
                i += 1
            elif level[s[i]] <= level[opt[-1]]:
                if s[i] == ')' and opt[-1] == '(':
                    opt.pop()
                    i += 1
                else:
                    b = int(num.pop())
                    a = int(num.pop())
                    signal = opt.pop()
                    num.append(eval("{} {} {}".format(a, signal, b)))

        return num[-1]

全部评论

相关推荐

昨天 16:47
门头沟学院 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:38
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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