思路:
定义数字栈和符号栈
- 如果提取的字符是一个操作数,将它压入操作数栈中。
- 如果提取的字符是一个+-*/的运算符,则处理符号栈顶的所有*和/的运算符,最后将新提取出来的运算符压入符号栈中。
- 如果提取出来的运算符是一个"(",则将它压入符号栈中。
- 如果提取出来的运算符是一个")",则重复处理符号栈顶的运算符,直到看到栈顶的运算符为")"
public class Test {
public static void main(String[] args) {
// String str = "2+8/2*(5+5+3)";
String str = "1+((2+3)*(4*5))";
char[] s = str.toCharArray();
Stack<Integer> num = new Stack<Integer>();
Stack<Character> fuhao = new Stack<Character>();
for(char c: s){
if(c == '+' || c == '-' || c == '*' || c == '/' ){ //遇到运算符,将栈中优先级更高的运算符弹出计算
while(!fuhao.isEmpty() && (fuhao.peek() == '*' || fuhao.peek() == '/')){
num.push(Test.compute(num, fuhao));
}
fuhao.push(c);
}else if( c =='('){
fuhao.push(c);
}else if(c == ')'){ //遇到右括号,一直运算,直到遇见左括号弹出
while(fuhao.peek() != '('){
num.push(Test.compute(num, fuhao));
}
fuhao.pop();
}else{
num.push((int)(c - '0'));
}
}
while(!fuhao.isEmpty()){
num.push(compute(num, fuhao));
}
System.out.println(num.peek());
}
static int compute(Stack<Integer> num, Stack<Character> fuhao){
int a = num.pop();
int b = num.pop();
char c = fuhao.pop();
int temp = 0;
if(c == '+'){
temp = b + a;
}else if(c == '-'){
temp = b - a;
}else if(c == '*'){
temp = b * a;
}else if(c == '/'){
temp = b / a;
}
return temp;
}
}