# leetcode225 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.

## 思路和代码

1.3+4-6-(5-9-(4)+6)-1 result = 3 sign=1 s=[]
2.3+4-6-(5-9-(4)+6)-1 result = 3 sign=1 s=[]
3.3+4-6-(5-9-(4)+6)-1 result = 7 sign=1 s=[]
4.3+4-6-(5-9-(4)+6)-1 result = 7 sign=-1 s=[]
5.3+4-6-(5-9-(4)+6)-1 result = 1 sign=-1 s=[]
6.3+4-6-(5-9-(4)+6)-1 result = 1 sign=-1 s=[]
7.3+4-6-(5-9-(4)+6)-1 result = 1 sign=1 s=[1,-1] 这时栈中的内容分别带包前面已经计算的值0和该位的正负形-1。同时因为即将开始一个新的计算，要将result初始化为0，sign初始化为1
8.3+4-6-(5-9-(4)+6)-1 result = 5 sign=1 s=[1,-1]
9.3+4-6-(5-9-(4)+6)-1 result = 5 sign=-1 s=[1,-1]
10.3+4-6-(5-9-(4)+6)-1 result = -4 sign=-1 s=[1,-1]
11.3+4-6-(5-9-(4)+6)-1 result = -4 sign=-1 s=[1,-1]
12.3+4-6-(5-9-(4)+6)-1 result = 0 sign=1 s=[1,-1,-4,-1]
13.3+4-6-(5-9-(4)+6)-1 result = 4 sign=1 s=[1,-1,-4,-1]
14.3+4-6-(5-9-(4)+6)-1 result = 4*(-1)-4=-8 sign=1 s=[1,-1] 遇到右括号，将栈中的上下文和当前的结果result进行计算得出括号中的最终结果
15.3+4-6-(5-9-(4)+6)-1 result = -8 sign=1 s=[1,-1]
16.3+4-6-(5-9-(4)+6)-1 result = -2*(-1) + 1=3 sign=1 s=[]
17.3+4-6-(5-9-(4)+6)-1 result = 3 sign=-1 s=[]
18.3+4-6-(5-9-(4)+6)-1 result = 2 sign=-1 s=[]

public  int calculate(String s) {
int len = s.length(), sign = 1, result = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
int sum = s.charAt(i) - '0';
while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) {
sum = sum * 10 + s.charAt(i + 1) - '0';
i++;
}
result += sum * sign;
} else if (s.charAt(i) == '+')
sign = 1;
else if (s.charAt(i) == '-')
sign = -1;
else if (s.charAt(i) == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (s.charAt(i) == ')') {
result = result * stack.pop() + stack.pop();
}

}
return result;
}