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-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)
, wherelet
is always the string"let"
, then there are 1 or more pairs of alternating variables and expressions, meaning that the first variablev1
is assigned the value of the expressione1
, the second variablev2
is assigned the value of the expressione2
, and so on sequentially; and then the value of this let-expression is the value of the expressionexpr
.
- An add-expression takes the form
(add e1 e2)
whereadd
is always the string"add"
, there are always two expressionse1, e2
, and this expression evaluates to the addition of the evaluation ofe1
and the evaluation ofe2
.
- A mult-expression takes the form
(mult e1 e2)
wheremult
is always the string"mult"
, there are always two expressionse1, e2
, and this expression evaluates to the multiplication of the evaluation ofe1
and the evaluation ofe2
.
- 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的更多相关文章
- [LeetCode] Parse Lisp Expression 解析Lisp表达式
You are given a string expression representing a Lisp-like expression to return the integer value of ...
- [Swift]LeetCode736. Lisp 语法解析 | Parse Lisp Expression
You are given a string expressionrepresenting a Lisp-like expression to return the integer value of. ...
- 736. Parse Lisp Expression
You are given a string expression representing a Lisp-like expression to return the integer value of ...
- 处理 javax.el.ELException: Failed to parse the expression 报错
在JSP的表达式语言中,使用了 <h3>是否新Session:${pageContext.session.new}</h3> 输出Session是否是新的,此时遇到了 j ...
- thymeleaf+layui加载页面渲染时TemplateProcessingException: Could not parse as expression
Caused by: org.attoparser.ParseException: Could not parse as expression: " {type: 'numbers'}, { ...
- org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression:
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression:
- could not parse as expression: "/login" (template: "include/include" - line 32, col 42)
<li><a href="login.html" th:href="/login">登录</a></li> or ...
- 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: ") ...
- Tomcat报failed to parse the expression [${xxx}]异常(javax.el.ELException)的解决方法
Tomcat 7 'javax.el.ELException' 的解决方式tomcat 7对EL表达式的语法要求比较严格,例如"${owner.new}"因包含关键字new就会导致 ...
随机推荐
- GitLab 如何在 Web 界面中 Merge branch
希望在 GitLab 中对 2 个 branch 进行合并,如何创建 Pull Request 并且如何进行合并呢? 在 GitLib 的 Web 界面中选择 Merge Requests 然后再界面 ...
- UVAlive 7414 Squeeze the Cylinders a,b,c三种步数 搜索+最短路
题意:给你n个点(n<=50),然后有些点之间会有一条路,路是单向的,每个回合让你走a,b,c三种步数中的任意一种(a,b,c<=100),问你最少需要多少个回合才能保证一定能从1点到达n ...
- HGOI 20191108 题解
Problem A 新婚快乐 一条路,被$n$个红绿灯划分成$n+1$段,从前到后一次给出每一段的长度$l_i$,每走$1$的长度需要$1$分钟. 一开始所有红绿灯都是绿色的,$g$分钟后所有红绿灯变 ...
- 在Idea中 的terminal 使用 git
参考该博客内容 http://blog.csdn.net/qq_28867949/article/details/73012300
- NotFoundError (see above for traceback): Key local3/weights not found in checkpoint
解决办法 原文 https://www.jianshu.com/p/2de8e01af88d with tf.Session() as sess: tf.get_variable_scope().re ...
- Django1.6 + jQuery Ajax + JSON 实现页面局部实时刷新
最近微信公众帐号要扩展做一个签到系统,签到结果在一个网页上实时更新,即页面局部刷新.我想用Ajax来实现,之前公众帐号是用的Django搭的,我查找了Django的官方文档,没有封装Ajax.网上有各 ...
- LeetCode 132. 分割回文串 II(Palindrome Partitioning II)
题目描述 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回符合要求的最少分割次数. 示例: 输入: "aab" 输出: 1 解释: 进行一次分割就可将 s ...
- python操作Elasticsearch (一、例子)
E lasticsearch是一款分布式搜索引擎,支持在大数据环境中进行实时数据分析.它基于Apache Lucene文本搜索引擎,内部功能通过ReST API暴露给外部.除了通过HTTP直接访问El ...
- css3网格效果(整理)
css3网格效果(整理) 一.总结 一句话总结: css3网格原理是渐变(linear-gradient)绘制图形,background-size属性指定重复的小单元的大小 多个渐变(linear-g ...
- opencv配置运行问题
opencv是图像处理常用的一个库文件,对于一些新手来说,配置完后运行,总会有这样或者那样的错误,会挫伤其学习积极性,这里将常见的几种错误列举出来,供其参考和使用. 方法/步骤第一种错误叫no suc ...