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.

Java:

public int calculate(String s) {
// delte white spaces
s = s.replaceAll(" ", ""); Stack<String> stack = new Stack<String>();
char[] arr = s.toCharArray(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ' ')
continue; if (arr[i] >= '0' && arr[i] <= '9') {
sb.append(arr[i]); if (i == arr.length - 1) {
stack.push(sb.toString());
}
} else {
if (sb.length() > 0) {
stack.push(sb.toString());
sb = new StringBuilder();
} if (arr[i] != ')') {
stack.push(new String(new char[] { arr[i] }));
} else {
// when meet ')', pop and calculate
ArrayList<String> t = new ArrayList<String>();
while (!stack.isEmpty()) {
String top = stack.pop();
if (top.equals("(")) {
break;
} else {
t.add(0, top);
}
} int temp = 0;
if (t.size() == 1) {
temp = Integer.valueOf(t.get(0));
} else {
for (int j = t.size() - 1; j > 0; j = j - 2) {
if (t.get(j - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(j));
} else {
temp += Integer.valueOf(t.get(j));
}
}
temp += Integer.valueOf(t.get(0));
}
stack.push(String.valueOf(temp));
}
}
} ArrayList<String> t = new ArrayList<String>();
while (!stack.isEmpty()) {
String elem = stack.pop();
t.add(0, elem);
} int temp = 0;
for (int i = t.size() - 1; i > 0; i = i - 2) {
if (t.get(i - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(i));
} else {
temp += Integer.valueOf(t.get(i));
}
}
temp += Integer.valueOf(t.get(0)); return temp;
}  

Python:

class Solution:
# @param {string} s
# @return {integer}
def calculate(self, s):
operands, operators = [], []
operand = ""
for i in reversed(xrange(len(s))):
if s[i].isdigit():
operand += s[i]
if i == 0 or not s[i-1].isdigit():
operands.append(int(operand[::-1]))
operand = ""
elif s[i] == ')' or s[i] == '+' or s[i] == '-':
operators.append(s[i])
elif s[i] == '(':
while operators[-1] != ')':
self.compute(operands, operators)
operators.pop() while operators:
self.compute(operands, operators) return operands[-1] def compute(self, operands, operators):
left, right = operands.pop(), operands.pop()
op = operators.pop()
if op == '+':
operands.append(left + right)
elif op == '-':
operands.append(left - right)

C++:

class Solution {
public:
int calculate(string s) {
int res = 0, sign = 1, n = s.size();
stack<int> st;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0') {
int num = 0;
while (i < n && s[i] >= '0') {
num = 10 * num + s[i++] - '0';
}
res += sign * num;
--i;
} else if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res *= st.top(); st.pop();
res += st.top(); st.pop();
}
}
return res;
}
};  

C++:

class Solution2 {
public:
int calculate(string s) {
stack<int> operands;
stack<char> operators;
string operand;
for (int i = s.length() - 1; i >= 0; --i) {
if (isdigit(s[i])) {
operand.push_back(s[i]);
if (i == 0 || !isdigit(s[i - 1])) {
reverse(operand.begin(), operand.end());
operands.emplace(stoi(operand));
operand.clear();
}
} else if (s[i] == ')' || s[i] == '+' || s[i] == '-') {
operators.emplace(s[i]);
} else if (s[i] == '(') {
while (operators.top() != ')') {
compute(operands, operators);
}
operators.pop();
}
}
while (!operators.empty()) {
compute(operands, operators);
}
return operands.top();
} void compute(stack<int>& operands, stack<char>& operators) {
const int left = operands.top();
operands.pop();
const int right = operands.top();
operands.pop();
const char op = operators.top();
operators.pop();
if (op == '+') {
operands.emplace(left + right);
} else if (op == '-') {
operands.emplace(left - right);
}
}
};

    

类似题目:

[LeetCode] 227. Basic Calculator II 基本计算器 II

All LeetCode Questions List 题目汇总

[LeetCode] 224. Basic Calculator 基本计算器的更多相关文章

  1. leetcode 224. Basic Calculator 、227. Basic Calculator II

    这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...

  2. [leetcode]224. Basic Calculator

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

  3. Java for LeetCode 224 Basic Calculator

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

  4. (medium)LeetCode 224.Basic Calculator

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

  5. 224 Basic Calculator 基本计算器

    实现一个基本的计算器来计算一个简单的字符串表达式. 字符串表达式可以包含左括号 ( ,右括号),加号+ ,减号 -,非负整数和空格 . 假定所给的表达式语句总是正确有效的. 例如: "1 + ...

  6. [LeetCode] 227. Basic Calculator II 基本计算器 II

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

  7. [LeetCode] Basic Calculator 基本计算器

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

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

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

  9. 【LeetCode】224. Basic Calculator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 栈 参考资料 日期 题目地址:https://lee ...

随机推荐

  1. Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.qingmu.seller.entity.OrderMaster

    org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before ...

  2. Linux 安装Anaconda 提示“bunzip2: command not found”

    问题: 安装Anaconda 过程中提示缺少“bunzip2” 解决思路: 由于缺少bunzip2 包,需要通过yum 方式安装bzip2 yum install -y bzip2 Linux bun ...

  3. postgres高可用学习篇二:通过pgbouncer连接池工具来管理postgres连接

    安装pgbouncer yum install libevent -y yum install libevent-devel -y wget http://www.pgbouncer.org/down ...

  4. django-安装nginx及fastdfs-nginx-module

    安装nginx及fastdfs-nginx-module 1. 解压缩 nginx-1.8.1.tar.gz 2. 解压缩 fastdfs-nginx-module-master.zip 3. 进入n ...

  5. 代码中的mysql语法问题

    今天在代码中写了mysql的删除语句 String lpinsuredSQL=" delete from lpinsured a where a.insuredid='?InsuredID? ...

  6. LG1378

    题目描述 在一个长方形框子里,最多有N(0≤N≤6)个相异的点,在其中任何一个点上放一个很小的油滴,那么这个油滴会一直扩展,直到接触到其他油滴或者框子的边界.必须等一个油滴扩展完毕才能放置下一个油滴. ...

  7. CI持续集成 -- git 与 gitlab

    版本控制系统概述 git Git基本概述 Git是一个免费的开源分布式版本控制系统,旨在快速高效地处理从小型到大型项目的所有内容. Git安装配置 #安装Git yum install -y git ...

  8. 【luoguP5091】【模板】欧拉定理

    题目链接 欧拉定理: 当\(a\),\(m\)互质时,\(a^{\phi(m)}\equiv 1 (mod ~ m)\) 扩展欧拉定理: 当\(B>\phi(m)\)时,\(a^B\equiv ...

  9. 洛谷P1560 蜗牛的旅行

    题目 搜索,注意判断特殊情况,并且区分开什么时候转弯什么时候停止.然后转弯的时候更是要注意是否会进入障碍. #include <bits/stdc++.h> using namespace ...

  10. Eclipse Maven问题小记

    Eclipse Maven Web工程报错:java.lang.ClassNotFoundException: ContextLoaderListener 原因:打包项目时没有把相关Maven依赖包打 ...