[LeetCode] 224. Basic Calculator 基本计算器
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 基本计算器的更多相关文章
- leetcode 224. Basic Calculator 、227. Basic Calculator II
		这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ... 
- [leetcode]224. Basic Calculator
		Implement a basic calculator to evaluate a simple expression string. The expression string may conta ... 
- Java for LeetCode 224 Basic Calculator
		Implement a basic calculator to evaluate a simple expression string. The expression string may conta ... 
- (medium)LeetCode  224.Basic Calculator
		Implement a basic calculator to evaluate a simple expression string. The expression string may conta ... 
- 224 Basic Calculator 基本计算器
		实现一个基本的计算器来计算一个简单的字符串表达式. 字符串表达式可以包含左括号 ( ,右括号),加号+ ,减号 -,非负整数和空格 . 假定所给的表达式语句总是正确有效的. 例如: "1 + ... 
- [LeetCode] 227. Basic Calculator II 基本计算器 II
		Implement a basic calculator to evaluate a simple expression string. The expression string contains ... 
- [LeetCode] Basic Calculator 基本计算器
		Implement a basic calculator to evaluate a simple expression string. The expression string may conta ... 
- [LeetCode] 772. Basic Calculator III 基本计算器之三
		Implement a basic calculator to evaluate a simple expression string. The expression string may conta ... 
- 【LeetCode】224. Basic Calculator 解题报告(Python)
		作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 栈 参考资料 日期 题目地址:https://lee ... 
随机推荐
- class Pagination(object)分页源码
			class Pagination(object): def init(self, current_page, all_count, per_page_num=10, pager_count=11): ... 
- RDD&Dataset&DataFrame
			Dataset创建 object DatasetCreation { def main(args: Array[String]): Unit = { val spark = SparkSession ... 
- django-全文解锁和搜索引擎
			安装和配置 全文检索安装 pip install django-haystack==2.5.1 # 2.7.0只支持django1.11以上版本 搜索引擎安装 pip install whoosh 安 ... 
- HDU - 5513 Efficient Tree(轮廓线DP)
			前言 最近学了基于连通性的状压DP,也就是插头DP,写了几道题,发现这DP实质上就是状压+分类讨论,轮廓线什么的也特别的神奇.下面这题把我WA到死- HDU-5531 Efficient Tree 给 ... 
- KMP + BZOJ 4974 [Lydsy1708月赛]字符串大师
			KMP 重点:失配nxtnxtnxt数组 意义:nxt[i]nxt[i]nxt[i]表示在[0,i−1][0,i-1][0,i−1]内最长相同前后缀的长度 图示: 此时nxt[i]=jnxt[i]=j ... 
- go 学习 (五):goroutine 协程
			一.goroutine 基础 定义 使用者分配足够多的任务,系统能自动帮助使用者把任务分配到 CPU 上,让这些任务尽量并发运作,此机制在Go中称作 goroutine goroutine 是 Go语 ... 
- 使用window.localStorage,window.localStorage记录点击次数
			<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ... 
- 使用nodejs+ harbor rest api 进行容器镜像迁移
			最近因为基础设施调整,需要进行harbor 镜像仓库的迁移,主要是旧版本很老了,不想使用,直接 打算部署新的,原以为直接使用复制功能就可以,但是发现版本差异太大,直接失败,本打算使用中间 版本过度进行 ... 
- Dart和JavaScript对比小结
			作为一名web前端来入门dart,新语言和我们熟悉的js有所差异,写dart的过程中容易受到原有思维的影响,这里把dart和js做一个对比总结,方便查找和熟悉. 变量声明 var 关键字 dart和j ... 
- c博客作业—分支,结构顺序
			1展现PTA总分 1 2 2本章学习类容总结 1常量和变量 常量:在运行中其值不变的量被称为常量,常量的类型通常是由书写格式决定,包括整型常量,实数型变量等等. 变量: 在运行中其值可变的量被称为变量 ... 
