题目:
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解答:
对应这类题型通用的做法是转成后缀表达式,然后根据逆波兰的计算方法进行计算。但这题比较特殊,因为它只有加减,我们可以通过化简括号进行计算,比如“1-(2-(4-6)+5)+3”
在这个表达式中,总共有1 2 4 6 5 3这几个数字,我们只要弄清楚这些数字的最终符号是什么,最终符号取决于数字前面的符号与数字前面所有左括号前面的那个符号的成绩,比如2:+1*(-1) 4:+1*(-1)*(-1) 5:+1*(-1)*(-1) 知道这个就应该看得懂代码了
代码:
public static int calculate(String s) {
char[] array=s.toCharArray();
Stack<Integer> stack=new Stack<>();
int result=0;
int sign=1;
stack.push(1);
for(int i=0;i<array.length;i++)
{
if(Character.isDigit(array[i]))
{
int num=array[i]-'0';
int j=i+1;
while(j<array.length&&Character.isDigit(array[j]))
{
num=10*num+array[j]-'0';
j++;
}
result+=sign*stack.peek()*num;
i=j-1;//j前面等于i+1
}
else if(array[i]=='+')
sign=1;
else if(array[i]=='-')
sign=-1;
else if(array[i]=='(')//记录左括号之前的那个符号,因为它会影响括号里面的所有运算符
{
stack.push(sign*stack.peek());
sign=1;
}
else if(array[i]==')')//保证之前左括号来的时候压入栈的那个符号不会影响后面那些不在括号中的运算
stack.pop();
else {
;//空格什么的就不操作
}
}
return result;
}