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), whereletis always the string"let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variablev1is assigned the value of the expressione1, the second variablev2is 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)whereaddis always the string"add", there are always two expressionse1, e2, and this expression evaluates to the addition of the evaluation ofe1and the evaluation ofe2.
- A mult-expression takes the form
(mult e1 e2)wheremultis always the string"mult", there are always two expressionse1, e2, and this expression evaluates to the multiplication of the evaluation ofe1and 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
expressionis 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
expressionis 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就会导致 ...
随机推荐
- VO、DTO、POJO、PO的区别
VO 即value object值对象.主要体现在视图的对象,对于一个WEB页面将整个页面的属性封装成一个对象.然后用一个VO对象在控制层与视图层进行传输交换. DTO 经过处理后的PO,可能增加或者 ...
- 在windows使用gvim的感受
用新下载的gvim写几行代码习惯一下,感觉vim用起来要比atom占用的内存少多了,更加的便捷.由于之前一直在用sublime text2,虽然我也很喜欢ST,但我还是抱着膜拜的心态来试了试gvim, ...
- LK光流算法公式详解
由于工程需要用到 Lucas-Kanade 光流,在此进行一下简单整理(后续还会陆续整理关于KCF,PCA,SVM,最小二乘.岭回归.核函数.dpm等等): 光流,简单说也就是画面移动过程中,图像上每 ...
- nginx关于uri的变量
在nginx中有几个关于uri的变量,包括$uri $request_uri $document_uri,下面看一下他们的区别 : $request_uri: /stat.php?id=1585378 ...
- centOS7搭建hadoop,zookeeper,hbase
1.配置ssh免密登录 (本人使用的是centOS7虚拟机) (本人未在root用户下安装,建议使用root用户,不然很麻烦!!) ① 本机无密钥登录 1.进入~/.ssh目录(若无,则执行一次ssh ...
- TensorFlow错误ValueError: No gradients provided for any variable
使用TensorFlow训练神经网络的时候,出现以下报错信息: Traceback (most recent call last): File "gan.py", line 1 ...
- Telerik JustDecompile
Free. For everyone. Forever. With an open source decompilation engine https://www.telerik.com/produc ...
- C# List中的ForEach
; List<string> aaa = new List<string>(){ "aaa", "bbb" }; aaa.ForEach ...
- linux下如何基于已有容器创建image并运行?
1. 通过docker ps命令先找到容器id,示例如下,123456789012就是我们要找的 jello@~$ docker ps CONTAINER ID IMAGE COMMAND CREAT ...
- Android视频直播全屏实现
/** * 添加直播组件 */ @SuppressLint("JavascriptInterface") private void addPlayerLive(final Subj ...