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 e1and 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.

因为input的结构比较固定,mult 和 add后面永远是接两个数或者表达式,或者一样一个,所以我们可以把input不断递归,使得最后input是一个数。这样就把问题解决了。

对于let,永远是多个pair+表达式,处理也是一样。

 class Solution {
public int evaluate(String expression) {
return helper(expression, new HashMap<>());
} private int helper(String expression, Map<String, Integer> map) {
if (isNumber(expression)) {
return Integer.parseInt(expression);
} if (isVariable(expression)) {
return map.get(expression);
}
List<String> tokens = parse(expression); if (tokens.get().equals("add")) {
return helper(tokens.get(), map) + helper(tokens.get(), map);
} else if (tokens.get().equals("mult")) {
return helper(tokens.get(), map) * helper(tokens.get(), map);
} else {
Map<String, Integer> newMap = new HashMap<>(map);
for (int i = ; i < tokens.size() - ; i += ) {
newMap.put(tokens.get(i), helper(tokens.get(i + ), newMap));
}
return helper(tokens.get(tokens.size() - ), newMap);
}
} private boolean isNumber(String expression) {
char firstLetter = expression.charAt();
return firstLetter == '-' || firstLetter == '+' || firstLetter <= '' && firstLetter >= '';
} private boolean isVariable(String expression) {
char firstLetter = expression.charAt();
return firstLetter <= 'z' && firstLetter >= 'a';
} private List<String> parse(String exp) {
List<String> parts = new ArrayList<>();
exp = exp.substring(, exp.length() - );
int startIndex = ;
while (startIndex < exp.length()) {
int endIndex = next(exp, startIndex);
parts.add(exp.substring(startIndex, endIndex));
startIndex = endIndex + ;
}
return parts;
} private int next(String expression, int startIndex) {
if (expression.charAt(startIndex) == '(') {
int count = ;
startIndex++;
while (startIndex < expression.length() && count > ) {
if (expression.charAt(startIndex) == '(') {
count++;
} else if (expression.charAt(startIndex) == ')') {
count--;
}
startIndex++;
}
} else {
while (startIndex < expression.length() && expression.charAt(startIndex) != ' ') {
startIndex++;
}
}
return startIndex;
}
}

如果问题里面没有let,代码可以简化为:

 class Solution {
public int evaluate(String expression) {
if (isNumber(expression)) {
return Integer.parseInt(expression);
} List<String> tokens = parse(expression); if (tokens.get().equals("add")) {
return evaluate(tokens.get()) + evaluate(tokens.get());
} else {
return evaluate(tokens.get()) * evaluate(tokens.get());
}
} private boolean isNumber(String expression) {
char firstLetter = expression.charAt();
return firstLetter == '-' || firstLetter == '+' || firstLetter <= '' && firstLetter >= '';
} private List<String> parse(String exp) {
List<String> parts = new ArrayList<>();
exp = exp.substring(, exp.length() - );
int startIndex = ;
while (startIndex < exp.length()) {
int endIndex = next(exp, startIndex);
parts.add(exp.substring(startIndex, endIndex));
startIndex = endIndex + ;
}
return parts;
} private int next(String expression, int index) {
if (expression.charAt(index) == '(') {
int count = ;
index++;
while (index < expression.length() && count > ) {
if (expression.charAt(index) == '(') {
count++;
} else if (expression.charAt(index) == ')') {
count--;
}
index++;
}
} else {
while (index < expression.length() && expression.charAt(index) != ' ') {
index++;
}
}
return index;
}
}

Parse Lisp Expression的更多相关文章

  1. [LeetCode] Parse Lisp Expression 解析Lisp表达式

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

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

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

  3. 736. Parse Lisp Expression

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

  4. 处理 javax.el.ELException: Failed to parse the expression 报错

    在JSP的表达式语言中,使用了  <h3>是否新Session:${pageContext.session.new}</h3>  输出Session是否是新的,此时遇到了  j ...

  5. thymeleaf+layui加载页面渲染时TemplateProcessingException: Could not parse as expression

    Caused by: org.attoparser.ParseException: Could not parse as expression: " {type: 'numbers'}, { ...

  6. org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression:

    org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression:

  7. could not parse as expression: "/login" (template: "include/include" - line 32, col 42)

    <li><a href="login.html" th:href="/login">登录</a></li> or ...

  8. layui表格数据渲染SpringBoot+Thymeleaf返回的数据时报错(Caused by: org.attoparser.ParseException: Could not parse as expression: ")

    layui table渲染数据时报错(Caused by: org.attoparser.ParseException: Could not parse as expression: ") ...

  9. Tomcat报failed to parse the expression [${xxx}]异常(javax.el.ELException)的解决方法

    Tomcat 7 'javax.el.ELException' 的解决方式tomcat 7对EL表达式的语法要求比较严格,例如"${owner.new}"因包含关键字new就会导致 ...

随机推荐

  1. 【csp模拟赛3】组合数学

    思路: 先排序,取最大的在剩余左边任意找k-1个数,所以是排列组合,费马小定理求逆元,预处理阶乘,注意要取模.. 代码: #include<cstdio> #include<iost ...

  2. ubuntu16.0.4 设置静态ip地址

    由于Ubuntu重启之后,ip很容易改变,可以用以下方式固定ip地址 1.设置ip地址 vi /etc/network/interface # The loopback network interfa ...

  3. python 获取数字在内存的内容

    #coding=utf- from struct import pack,unpack byte=pack('f',1.5) print(byte) print([i for i in byte]) ...

  4. js反混淆

    var esprima = require('esprima') var escodegen = require('escodegen') content = "function _0x35 ...

  5. dos切换其他目录加参数/D

    D:\>cd /D c:\Windows c:\Windows> 不加参数/D 无法切换到另一个盘符

  6. openfalcon架构及相关服务配置详解(转)

    一:openfalcon组件 1.falcon-agent 数据采集组件 agent内置了一个http接口,会自动采集预先定义的各种采集项,每隔60秒,push到transfer. 2.transfe ...

  7. BigDecimal常用的加减乘除算法、比较大小、不展示多余的零、保存两位小数点

    项目中涉及到了BigDecimal的加.减.乘.比较大小.精确度的问题.所以在此总结一下,方便以后复习. //加法 BigDecimal coins = new BigDecimal("0& ...

  8. openapi and light-4j

    light-4j项目支持openapi规范,本文介绍一下参照相关demo做的上传功能. openapi.yaml,按照规范编写内容,/openapi/swagger可以查看对应的swagger页面,A ...

  9. OUC_Summer Training_ DIV2_#12(DP1) 723

    这一次是做练习,主要了解了两个算法,最大子矩阵和,最长上升子序列. 先看题好啦. A - To The Max Time Limit:1000MS     Memory Limit:32768KB   ...

  10. macos npm + node 环境启动问题排查

    MacOS安装npm全局包的权限问题 解决办法:修改npm包所安装目录的权限:sudo chown -R $USER /usr/local   然后输入密码就可以了 deMBP:~ $ sudo ch ...