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
}
};

Lintcode: Expression Evaluation (Basic Calculator III)的更多相关文章

  1. [LeetCode] Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  2. [LeetCode] 772. Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  3. 【leetcode】Basic Calculator III

    题目如下: Implement a basic calculator to evaluate a simple expression string. The expression string may ...

  4. leetcode 772.Basic Calculator III

    这道题就可以结合Basic Calculator中的两种做法了,分别是括号运算和四则运算的,则使用stack作为保持的结果,而使用递归来处理括号内的值的. class Solution { publi ...

  5. LintCode "Expression Evaluation"

    This is sth. for me to learn.. https://github.com/kamyu104/LintCode/blob/master/C++/expression-evalu ...

  6. Basic Calculator I && II && III

    Basic Calculator I Implement a basic calculator to evaluate a simple expression string. The expressi ...

  7. Basic Calculator - Stack(表达式计算器)

    978. Basic Calculator https://www.lintcode.com/problem/basic-calculator/description public class Sol ...

  8. [LeetCode] Basic Calculator IV 基本计算器之四

    Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...

  9. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

随机推荐

  1. apache的prefork的详解

    apache的prefork的参数详解:ServerLimit 2000 这是最大进程数的阀值StartServers 25  启动时建立的子进程MinSpareServers 25 最小空闲进程Ma ...

  2. jquery用法大全

    jQuery 选择器 选择器                  实例                                   选取 *                          $ ...

  3. bug 发表文章不显示图片

    bug 描述: 现象是我们这不能发布图片, 测试说患教方向是可以正常发布图片的(还是要感激测试,正是他们鞭策我们不断挑战困难,解决之,从而提高自己姿势水平). 图片没上传上去, 服务端协助查找发现没调 ...

  4. 【转】配置 VS 2015 开发跨平台手机应用

    为了使用 VS 2015 开发跨平台手机应用,VS 2015 装了很多次,遇到了很多坑,才终于弄明白怎样配置才能正常使用C#开发手机应用,现把步骤分享给大家,以免大家少走弯路. 运行环境: Windo ...

  5. Summary of java stream classes

    Java’s stream classes are good for streaming sequences of bytes, but they’re not good for streaming ...

  6. 蓝牙BLE MTU规则与约定

    1. 问题引言: 想在gatt client上(一般是手机上)传输长一点的数据给gatt server(一般是一个Bluetooth smart设备,即只有BLE功能的设备),但通过 writeCha ...

  7. CDH商业版本的搭建(hadoop+hive+sqoop)

    一:准备工作 1.步骤 1)hadoop ->下载解压 ->修改配置文件 ->hadoop-env JAVA_HOME ->core-site fs.defaultFS had ...

  8. Express创建并运行node项目(Jade和EJS模版引擎)

    1.创建Node项目 [Jade模板] > express nodeJade express创建项目若不显示指定模板,默认使用Jade,以下写法都可以: express -jade nodeJa ...

  9. 常用jQuery代码02

    一.each函数拿到每个元素的宽度 setTimeout(function () { $(".sticker_list img").each(function () { var W ...

  10. ArcGIS Engine开发之旅04---ARCGIS接口详细说明

    原文:ArcGIS Engine开发之旅04---ARCGIS接口详细说明 ArcGIS接口详细说明... 1 1.      IField接口(esriGeoDatabase)... 2 2.    ...