# [leetcode]Basic Calculator(java)

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 int calculate(String s) {
Stack<Character> charStack = new Stack<Character>();
Stack<Integer> intStack = new Stack<Integer>();

int index = -1;
int length = s.length();
char tmpChar;
int top1,top2;
while((++index)<length){
if((tmpChar=s.charAt(index)) == ' ')//ignore blank
continue;
switch (tmpChar) {
case '(':
charStack.push(tmpChar);
break;
case '-':
case '+':
if(charStack.isEmpty())
charStack.push(tmpChar);
else if(charStack.peek()=='(')
charStack.push(tmpChar);
else {
char op = charStack.pop();
charStack.push(tmpChar);
switch (op) {
case '+':
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top1+top2);
break;
default:
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top2-top1);
break;
}
}
break;
case ')':
while((tmpChar=charStack.pop())!='('){
switch (tmpChar) {
case '+':
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top1+top2);
break;
case '-':
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top2-top1);
break;
}
}
break;
default://number
//form intnumber,and push to intstack
int number = 0;
while(tmpChar>='0'&&tmpChar<='9'){
number = number*10+tmpChar-'0';
if(++index<length)
tmpChar = s.charAt(index);
else
break;
}
intStack.push(number);
index--;
break;
}
}
//process the last one
while(!charStack.isEmpty()){
tmpChar = charStack.pop();
switch (tmpChar) {
case '+':
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top2+top1);
break;//+
default:
top1 = intStack.pop();
top2 = intStack.pop();
intStack.push(top2-top1);
break;//-
}
}
return (intStack.isEmpty())?0:intStack.pop();
}

 public int calculate(String s){
int length = s.length();
Stack<Integer> signStack  = new Stack<Integer>();
signStack.push(1);//object
signStack.push(1);//firstElement sign

int index = -1;
char tmpChar;
int result = 0;

while(++index<length){
if((tmpChar=s.charAt(index))==' ')
continue;//ignore blank
switch (tmpChar) {
case '+':
case '(':
signStack.push(signStack.peek());
break;
case '-':
signStack.push(-1*(signStack.peek()));
break;
case ')':
signStack.pop();
break;
default://digital
int num=0;
while(tmpChar>='0'&&tmpChar<='9'){
num=num*10+tmpChar-'0';
if(++index<length)
tmpChar = s.charAt(index);
else
break;
}
result+=signStack.pop()*num;
index--;
break;
}
}
return result;
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode]Basic Calculator(java) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)