LeetCode 736. Parse Lisp Expression

该博客介绍了一种基于LISP的表达式解析和计算方法,通过前序表达式实现。文章重点讲解了如何扩展Exp类以支持let赋值语句,并详细展示了如何构建和评估此类表达式树。通过对表达式从后向前遍历并压栈,最后统一出栈计算,巧妙地处理了计算逻辑。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

给出类似于lisp的表达式(前序表达式),新加入了let赋值语句

注意:把每一句子表达式都抽象成了Exp对象,一个父exp包含了1个或者多个子Exp,从后向前遍历压栈,到最后统一出栈计算,妙啊!

class Solution {
    class Exp {
        Stack<Exp> exps;
        String op;
        Exp parent;

        Exp(Exp from) {
            this.exps = new Stack<>();
            this.parent = from;
        }

        int evaluate(Map<String, Integer> vars) {
            if (op.equalsIgnoreCase("add")) {
                return exps.pop().evaluate(vars) + exps.pop().evaluate(vars);
            } else if (op.equalsIgnoreCase("mult")) {
                return exps.pop().evaluate(vars) * exps.pop().evaluate(vars);
            } else if (op.equalsIgnoreCase("let")) {
                Map<String, Integer> nextVars = new HashMap<>(vars);
                while (exps.size()>1) {
                    String varName = exps.pop().op;
                    int val = exps.pop().evaluate(nextVars);
                    nextVars.put(varName, val);
                }
                return exps.pop().evaluate(nextVars);
            } else {
                if (Character.isLetter(op.charAt(0))) {
                    return vars.get(op);
                } else {
                    return Integer.parseInt(op);
                }
            }
        }
    }
    
    Exp buildTree(String exp) {
        Exp root = new Exp(null), cur = root;
        int n = exp.length()-1;
        while (n >=0) {
            char c = exp.charAt(n);
            if (c==')') {
                Exp next = new Exp(cur);
                cur.exps.push(next);
                cur = next;
            } else if (c=='(') {
                cur.op = cur.exps.pop().op;
                cur = cur.parent;
            } else if (c != ' '){
                int pre = n;
                while (pre>=0 && exp.charAt(pre)!='(' && exp.charAt(pre)!=' ')
                    pre--;
                Exp next = new Exp(cur);
                next.op = exp.substring(pre+1, n+1);
                cur.exps.push(next);
                n=pre+1;
            }
            n--;
        }
        return root.exps.pop();
    }
    
    public int evaluate(String exp) {
        return buildTree(exp).evaluate(new HashMap<>());
    }
}

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值