[Leetcode] 736. Parse Lisp Expression 解题报告

leetcode(含python、java、c)代码合集 leetcode(含python、java、c)代码合集,目录清晰,适合刷leetcode的朋友参考 立即下载

题目:

You are given a string expression representing a Lisp-like expression to return the integer value of.

The syntax for these expressions is given as follows.

  • An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.

  • (An integer could be positive or negative.)

  • A let-expression takes the form (let v1 e1 v2 e2 ... vn en expr), where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let-expression is the value of the expression expr.

  • An add-expression takes the form (add e1 e2) where add is always the string "add", there are always two expressions e1, e2, and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2.

  • A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", there are always two expressions e1, e2, and this expression evaluates to the multiplication of the evaluation of e1 and the evaluation of e2.

  • For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names "add", "let", or "mult" are protected and will never be used as variable names.

  • Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.

    Evaluation Examples:

    Input: (add 1 2)
    Output: 3
    
    Input: (mult 3 (add 2 3))
    Output: 15
    
    Input: (let x 2 (mult x 5))
    Output: 10
    
    Input: (let x 2 (mult x (let x 3 y 4 (add x y))))
    Output: 14
    Explanation: In the expression (add x y), when checking for the value of the variable x,
    we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
    Since x = 3 is found first, the value of x is 3.
    
    Input: (let x 3 x 2 x)
    Output: 2
    Explanation: Assignment in let statements is processed sequentially.
    
    Input: (let x 1 y 2 x (add x y) (add x y))
    Output: 5
    Explanation: The first (add x y) evaluates as 3, and is assigned to x.
    The second (add x y) evaluates as 3+2 = 5.
    
    Input: (let x 2 (add (let x 3 (let x 4 x)) x))
    Output: 6
    Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
    of the final x in the add-expression.  That final x will equal 2.
    
    Input: (let a1 3 b2 (add a1 1) b2) 
    Output 4
    Explanation: Variable names can contain digits after the first character.
    
    

    Note:

  • The given string expression is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.
  • The length of expression is at most 2000. (It is also non-empty, as that would not be a legal expression.)
  • The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.

    思路:

    采用递归思路对问题进行求解,分为如下几种情况进行处理:

    1)如果表达式是变量,那么我们就在变量表中查找到变量的名称,并且返回;如果表达式是值,则我们直接返回值。

    2)对于let而言,我们首先获得变量的名称,然后解析其对应的表达式,最后将变量的值和变量名的对应加入到表中。例如对于(let x (add 2 3) x),我们首先得到变量名x,然后解析表达式(add 2, 3),得到值5,然后赋值x = 5。对于最后一个x,我们在解析的过程中,直接在映射表中找到其对应的值5,并返回。

    3)对于add而言,我们首先解析第一个表达式,然后解析第二个表达式,最后将两者相加,并返回。例如对于"(add (add 2 3) (add 3 4))"而言,第一个表达式是“(add 2 3)”,第二个表达式是"(add 3 4)",解析后我们分别得到5和7.所以最后返回12 = 5 + 7即可。

    4)对于mult而言,我们解析的方式类似于add。

    代码:

    class Solution {
    public:
        int evaluate(string expression) {
            unordered_map<string, int> myMap;
            return help(expression, myMap);
        }
    private:
        int help(string expression,unordered_map<string,int> myMap) {
            if ((expression[0] == '-') || (expression[0] >= '0' && expression[0] <= '9')) {
                return stoi(expression);
            }
            else if (expression[0] != '(') {
                return myMap[expression];
            }
            //to get rid of the first '(' and the last ')'
            string s = expression.substr(1, expression.size() - 2);
            int start = 0;
            string word = parse(s, start);
            if (word == "let") {
                while (true) {
                    string variable = parse(s, start);
                    //if there is no more expression, simply evaluate the variable
                    if (start > s.size()) {
                        return help(variable, myMap);
                    }
                    string temp = parse(s, start);
                    myMap[variable] = help(temp, myMap);                    
                }
            }
            else if (word == "add") {
                return help(parse(s, start), myMap) + help(parse(s, start), myMap);
            }
            else if (word == "mult") {
                return help(parse(s, start), myMap) * help(parse(s, start), myMap);
            } 
        }
        string parse(string &s,int &start) {    //function to seperate each expression
            int end = start + 1, temp = start, count = 1;
            if (s[start] == '(') {
                while (count != 0) {
                    if (s[end] == '(') {
                        ++count;
                    }
                    else if (s[end] == ')') {
                        --count;
                    }
                    ++end;
                }
            }
            else {
                while (end < s.size() && s[end] != ' ') {
                    ++end;
                }
            }
            start = end + 1;
            return s.substr(temp, end - temp);
        }
    };
SAP-ABAP:SAP库存管理核心增强:IF_EX_MB_DOCUMENT_BADI 深度解析 SAP库存管理核心增强:IF_EX_MB_DOCUMENT_BADI 深度解析 阅读详情

相关推荐

新手必看:5分钟搞定Unitree Go1机器狗Gazebo仿真运动控制(附按键图解)

本文为新手提供了Unitree Go1机器狗在Gazebo仿真环境中实现运动控制的快速指南。通过5分钟极简配置和按键图解,帮助开发者快速掌握宇树科技明星产品的基础操作,包括环境搭建、仿真启动和运动控制技巧,适合零基础用户快速上手。

weixin_42550597的博客 300

maven配置文件中警告This expression evaluates to 4.2.4.RELEASE The property is defined in cn.的处理方法

在pom.xml中出现警告如下:This expression evaluates to 4.2.4.RELEASE The property is defined in cn.itcast:web_parent:0.0.1-SNAPSHOT这句话:This expression evaluates to  4.2.4.RELEASE  The property is defined in cn....

冰糖棉花的博客 3612

从零构建:Esp32+Esp-IDF驱动ST7789屏幕并集成LVGL图形库

本文详细介绍了如何从零开始使用Esp32和Esp-IDF驱动ST7789屏幕并集成LVGL图形库。内容涵盖环境准备、SPI驱动配置、屏幕初始化、LVGL图形库集成及常见问题排查,帮助开发者快速实现高效稳定的显示解决方案。

weixin_42657024的博客 524

Leetcode736 单调递增的数字 (贪心策略)

贪心策略,从左到右,从高位到低位不断的分析数字,如果当前位是属于上升段,那么不断向右移动。如果移动到最右端,当前数字满足要去。 若否,那么将前一位-1,看看前一位是否满足要求,如果已经满足要求,那么将后面的位全部变为9,即得到满足要求的答案。 如果当前位-1不满足递增要求,说明要继续向前判断,直到满足要求后,将后面的所有位都变为9. class Solution { public: int monotoneIncreasingDigits(int N) { s...

wwxy1995的博客 208

AI辅助游戏开发实战:Kimi K3提升Unity开发效率与代码质量

在游戏开发领域,有限状态机(FSM)是构建角色AI行为逻辑的核心设计模式,它通过定义明确的状态和转换条件,使游戏实体能够智能地响应环境变化。其原理在于将复杂的行为分解为离散的状态节点,并通过事件驱动状态切换,从而实现清晰、可维护的AI架构。这项技术的价值在于显著提升了游戏角色的行为真实感和开发效率,被广泛应用于NPC行为控制、角色动画管理、UI流程等场景。随着AI编程助手的兴起,开发者现在可以借助如Kimi K3这类工具,通过自然语言指令快速生成和优化FSM等复杂系统的代码框架,将更多精力投入到核心玩法与性

weixin_30430677的博客 407

【实战指南】OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

hampeter的博客 1800

leetcode 736. Parse Lisp Expression Lisp表达式解析

You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, a let-...

JackZhangNJU的专栏 662

STM32G4系列数字LLC控制程序开发实战

本文详细介绍了基于STM32G4系列MCU的数字LLC控制程序开发全流程。从开发环境搭建、中断服务函数设计,到核心的电压环PID算法、Burst模式控制、状态机设计以及软启动优化,提供了完整的实战代码和关键参数调试经验,帮助开发者高效实现高性能数字电源控制。

weixin_29185493的博客 278

736. Parse Lisp Expression

You are given a stringexpressionrepresenting a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer,...

weixin_30377461的博客 118

基于Simulink的四足机器人楼梯攀爬仿真模型

构建一个基于Simulink的四足机器人楼梯攀爬仿真模型,旨在模拟四足机器人在面对楼梯等障碍时的运动控制和稳定性调整。以下是一个详细的步骤指南,帮助你从零开始创建这样一个仿真模型。

xiaoheshang_123的博客 247

拿下华为性格测试!

华为性格测试指南

weixin_41171614的博客 5264

你需要明白的聚合函数{[[ALL | DISTINCT] expression |*}

1. 在聚合函数中,可以用ALL 或者DISTINCT这样的关键字 2. 当Count()作用于某一特定列(Column),和以“*”作为参数时的区别是当Count(列名)碰到“Null”值时不会将其计算在内 转载于:https://www.cnblogs.com/flysun0311/archive/2013/02/23/2923396.html...

weixin_34270865的博客 1734

springboot+vue项目基础开发(12)vue项目的搭建

在src目录下新建 api,utils,views文件夹。删除componets目录下自动生成的所有文件。在utils文件夹下创建request.js。启动项目,记得是要在管理员下启动。

m0_58498702的博客 152

《leetcode》:Expression Add Operators

题目Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Ex

wojiushimogui的博客 523

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

LeetCode //C - 736. Parse Lisp Expression

The abstract of this article can be summarized as follows: Lisp expression parsing algorithm This paper proposes a recursive solution for parsing Lisp-like expressions. The algorithm handles nested expressions through recursive descent parsing and uses a s

Made in Code 1172

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

LeetCode 736 Parse Lisp Expression

You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, a let-ex...

katrina95的博客 276

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

leetcode 736. 困难题 Parse Lisp Expression Lisp 语法解析

若是数字,若到了最后一个字符则返回该数字,if(i==expre.size()-1) { return kk; },若深度不同且全局变量含有该字符串,则记录用来递归的后续恢复,并修改全局变量的值 if(ump.count(pre)!=0 && ump[pre].second!=level) {tmp_UMP[pre] = ump[pre];} ump[pre] = {kk, level};当该字符是’(',则需要用栈拿到括号内的字符串,并且索引累加i += trg.size() + 1;,递归拿到结果数字,

邹九的个人博客 386

leetcode 736. Parse Lisp Expression

You are given a stringexpressionrepresenting a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, a le...

cmy203的博客 263

[Swift]LeetCode736. Lisp 语法解析 | Parse Lisp Expression

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30783629的博客 281

LeetCode 736. Parse Lisp Expression

给出类似于lisp的表达式(前序表达式),新加入了let赋值语句 注意:把每一句子表达式都抽象成了Exp对象,一个父exp包含了1个或者多个子Exp,从后向前遍历压栈,到最后统一出栈计算,妙啊! class Solution { class Exp { Stack<Exp> exps; String op; Exp parent; Exp(Exp from) { this.exps = new

大乐的博客 348

Hive sql:列名为关键字如何 select

背景 group 是数据库关键字,直接 select group 报错如下: line 2:8: mismatched input 'group'. Expecting: '*', 'ALL', 'DISTINCT', <expression> 翻译:第2:8行:不匹配的输入’group’。期望:’*’,‘ALL’, ‘DISTINCT’, 查询网上,说使用反引号可以。 select `group` 结果还是报错,如下: line 2:8: backquoted identifiers ar

零度的博客 8022

JavaScript循环介绍:For循环,While循环,Do ... while循环等

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns f...

cumian8165的博客 1026

LeetCode 736. Lisp 语法解析

736. Lisp 语法解析 【DFS】字符串解析+递归首先提取出操作符后,后面按照子表达式的概念进行拆分,拆分后放在一个list中。如果操作符为let,那么两两遍历,第一个字符串作为key,第二个字符串是一个表达式,继续递归解析,将返回值作为value一起存入map中。然后返回最后一个字符串的解析值。如果操作符为add,那么只需要将两个表达式的解析结果相加返回。操作符为mult同理。...

Sasakihaise_的博客 2639

736. Lisp 语法解析

给定一个类似 Lisp 语句的表达式 expression,求出其计算结果。 表达式语法如下所示: 表达式可以为整数,let 语法,add 语法,mult 语法。表达式的结果总是一个整数。 (整数可以是正整数、负整数、0) let 语法表示为(let v1 e1 v2 e2 ... vn en expr),其中let语法总是以字符串"let"来表示,接下来会跟随一个或多个交替变量或...

Umbrella Corporation 7250

LWC 60:736. Parse Lisp Expression

LWC 60:736. Parse Lisp Expression传送门:736. Parse Lisp ExpressionProblem: You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these

Demon-初来驾到 936
上一篇: [Leetcode] 735. Asteroid Collision 解题报告
下一篇: [Leetcode] 737. Sentence Similarity II 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值