Basic Calculator with parenthesis
Leetcode 224 加上parenthesis, 例如"2+((8+2)+(3-999))",返回计算结果。
class Solution {
public int calculate(String s) {
Deque<Character> queue = new LinkedList<>();
for(int i = 0; i< s.length(); i++)
{
if(s.charAt(i) != ' ')
{
queue.addLast(s.charAt(i));
}
}
return helper(queue);
}
public int helper(Deque<Character> queue)
{
Deque<Integer> stack = new LinkedList<>();
int num = 0;
char preSign = '+';
while(queue.size() > 0)
{
char current = queue.removeFirst();
if(isNumber(current))
{
num = num * 10 + (current - '0');
}
if(current == '(')
{
num = helper(queue);
}
if(!isNumber(current) || queue.size() == 0)
{
switch(preSign)
{
case '+': stack.push(num); break;
case '-': stack.push(-num); break;
}
preSign = current;
num = 0;
}
if(current == ')') break;
}
int res = 0;
while(stack.size() > 0)
{
res += stack.removeLast();
}
return res;
}
public boolean isNumber(char c)
{
return c >= '0' && c <= '9';
}
}
Last updated