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就会导致 ...
随机推荐
- php+上传超大文件
demo下载:http://t.cn/Ai9p3CKQ 教程:http://t.cn/Aipg9uUK 一提到大文件上传,首先想到的是啥??? 没错,就是修改php.ini文件里的上传限制,那就是up ...
- linux manual free memory
/proc/sys/vm/drop_caches (since Linux 2.6.16)Writing to this file causes the kernel to drop clean ca ...
- Codeforces Round #369 (Div. 2) C 基本dp+暴力
C. Coloring Trees time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- 解决xftp远程连接后出现中文乱码
- 关于Math.random()
关于 Math.random() ,以前经常搞混淆,这次写个笔记专门记录下: Math.random() : 返回的是 0~1 之间的一个随机小数0<=r<1,即[0,1); 注意:这里 ...
- ubuntu 14.04 升级到18.04
http://www.360doc.com/content/18/0929/09/35082563_790606785.shtml
- [学习]sentinel中的DatatSource(一) ReadableDataSource
sentinel是今年阿里开源的高可用防护的流量管理框架. git地址:https://github.com/alibaba/Sentinel wiki:https://github.com/alib ...
- OpenCV中出现“Microsoft C++ 异常: cv::Exception,位于内存位置 0x0000005C8ECFFA80 处。”的异常
对于OpenCV的安装 要感谢网友空晴拜小白提供的教程 链接如下: https://blog.csdn.net/sinat_36264666/article/details/73135823?ref= ...
- C++ STL——类型转换
目录 一 类型转换 注:原创不易,转载请务必注明原作者和出处,感谢支持! 注:内容来自某培训课程,不一定完全正确! 一 类型转换 类型转换的含义是通过改变一个变量的类型为别的类型从而改变变量的表示方式 ...
- Django博客系统
零.创建项目及配置 一.编写 Model 层的代码 二.配置 admin 页面 三.根据需求定制 admin