Description:

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.

用两个操作栈来处理,具体见代码。

public class Solution {
public static int calculate(String s) {
Stack<Integer> num = new Stack<>();
Stack<Character> op = new Stack<>();
op.push('+');
int n = s.length();
if(n < 1) return 0;
for(int i=0; i<n; ) {
if(s.charAt(i) == ' ') {
i ++;
}
else if(s.charAt(i) == '(') {
op.push('(');
op.push('+');
i ++;
}
else if(isOp(s.charAt(i))) {
op.push(s.charAt(i));
i ++;
}
//523 +-(++
else if(s.charAt(i) == ')') {
int res = 0;
while (!op.empty() && !(op.peek() == '(')) {
int temp = num.peek();
if (op.peek() == '-') temp = -temp;
res += temp;
num.pop();
op.pop();
}
System.out.println(res);
op.pop();
num.push(res);
i ++;
}
else {
int temp = 0;
while(i < n && isDigit(s.charAt(i))) {
temp = temp * 10;
temp += s.charAt(i) - '0';
i ++;
} num.push(temp);
} }
int res = 0;
while (!op.empty()) {
int temp = num.peek();
if (op.peek() == '-') temp = -temp;
res += temp;
num.pop();
op.pop();
} return res; }
public static boolean isOp(char c) {
if(c == '+' || c == '-') {
return true;
}
else {
return false;
}
}
public static boolean isDigit(char c) {
if(c >= '0' && c <='9') {
return true;
}
else {
return false;
}
}
}

最新文章

  1. wex5 实战 省市县三级联动与地址薄同步
  2. MySQL中优化sql语句查询常用的种方法
  3. Theano2.1.14-基础知识之理解为了速度和正确性的内存别名
  4. iOS边练边学--AFNetWorking框架GET、Post、Download、Upload,数据解析模式以及监控联网状态
  5. phonegap修改软件名称和图标
  6. Entity Framework 并发处理借鉴
  7. 并发容器之CopyOnWriteArrayList(转载)
  8. fcntl记录锁实例
  9. TPL(Task Parallel Library)多线程、并发功能
  10. Asp.Net部分面试题
  11. javascript中强制类型转换
  12. Socket 学习(三)
  13. 教你如何解决Sublime Text 3使用中出现的中文乱码问题
  14. Win10 + MySQL + Tableu + PPT + 可视化方案
  15. tf.reducemean()到底是什么意思?
  16. h5的改进:
  17. PPTP服务端与客户端 修改默认PPTP默认端口1723
  18. supervisor的command执行两条命令
  19. dvwa 源码分析(三) --- config.inc.php分析
  20. C++中的字节对齐分析

热门文章

  1. Apache Httpd 反向代理配置 (笔记)
  2. JAVA里使用CKEditor和CKFinder的配置
  3. kafkaStream解析json出错导致程序中断的解决方法
  4. css样式DEMO
  5. [oracle] oracle-myibatis-整理
  6. thinkphp 连接mssql 当local失效时
  7. Intellij IDEA Module 的Language Level的问题
  8. 将ORACLE数据库更改为归档模式;写出步骤
  9. peek函数的用法
  10. linux -- 终端执行可执行文件