Lintcode: Expression Evaluation (Basic Calculator III)
2016-02-02 13:16
661 查看
Given an expression string array, return the final result of this expression Have you met this question in a real interview? Yes Example For the expression 2*6-(23+7)/(1+2), input is [ "2", "*", "6", "-", "(", "23", "+", "7", ")", "/", (", "1", "+", "2", ")" ], return 2 Note The expression contains only integer, +, -, *, /, (, ).
这道题其实应该算Basic Calculator III. 参考了http://blog.csdn.net/nicaishibiantai/article/details/45740649
思路就是两个stack,一个存数字一个存符号。如果遇到数字直接存到数字stack;如果遇到符号,有几种情况:
1.当前符号比上一个符号优先级高,比如* 高于+,那么直接进栈
2.当前符号低于上一个,那么就要把所有已经在stack里面优先于当前符号的全算完,再推进当前符号
3.当前符号是“(”,直接push
4.当前符号是“)”,就要把所有“(”以前的符号全部算完
public class Solution { /** * @param expression: an array of strings; * @return: an integer */ public int evaluateExpression(String[] expression) { // write your code here Stack<Integer> integers = new Stack<Integer>(); Stack<String> ops = new Stack<String>(); int i = 0; while (i < expression.length) { String cur = expression[i]; if (isOp(cur)) { // current string is an op if (cur.equals("(")) ops.push(cur); else if (cur.equals(")")) { while (ops.size()>0 && !ops.peek().equals("(")) { integers.push(calc(integers.pop(), integers.pop(), ops.pop())); } ops.pop(); } else { // +,-,*,/ while (ops.size()>0 && precede(cur, ops.peek())) { integers.push(calc(integers.pop(), integers.pop(), ops.pop())); } ops.push(cur); } } else integers.push(Integer.parseInt(cur)); // current String is an integer, push to integer stack i++; } while (!ops.isEmpty()) { integers.push(calc(integers.pop(), integers.pop(), ops.pop())); } return integers.isEmpty()? 0 : integers.pop(); } public boolean isOp(String input) { if (input.equals("+") || input.equals("-") || input.equals("*") || input.equals("/") || input.equals("(") || input.equals(")")) return true; return false; } public int calc(int a, int b, String op) { if (op.equals("+")) return a+b; else if (op.equals("-")) return b-a; else if (op.equals("*")) return a*b; else return b/a; } public boolean precede(String a, String b) { if (b.equals("*") || b.equals("/")) return true; if (b.equals("+") || b.equals("-")) { if (a.equals("*") || a.equals("/")) return false; else return true; } return false; //case like (a+b) 到第一个+号时,+和(比应该return false } };
相关文章推荐
- lua垃圾回收机制
- Lua中的元表与元方法
- 用LuaBridge为Lua绑定C/C++对象
- lua class
- Lua5.3 异或操作的一个坑
- lua协程用法举例
- lua os.time与os.date的简单用法
- vim+lua
- lua实现单例模式
- lua-excel助手
- lua 和 luajit 性能对比测试
- lua 函数回调技巧
- Leetcode || Evaluate Reverse Polish Notation
- 【Lua】观察者模式在Lua中的实现
- Evaluation of —OLSR—OSPF—BATMAN—AODV
- Evaluating Network Simulation Tools—CORE—NS3—MANET
- Lua消息处理集合
- Lua检查非空
- Lua增加ccbi
- Lua重新加载Lua文件