java写一个时间复杂度低的带括号计算器
时间: 2023-10-31 17:11:48 浏览: 160
分析算法时间复杂度java.zip
好的,我可以帮你回答这个问题。下面是一个使用栈来实现带括号的计算器的 Java 代码,时间复杂度为 O(n)。
```java
import java.util.Stack;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String expression = sc.nextLine();
System.out.println("结果为:" + evaluate(expression));
}
public static int evaluate(String expression) {
Stack<Integer> numbers = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c >= '0' && c <= '9') {
int number = c - '0';
while (++i < expression.length() && expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
number = number * 10 + (expression.charAt(i) - '0');
}
i--;
numbers.push(number);
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (operators.peek() != '(') {
numbers.push(apply(operators.pop(), numbers.pop(), numbers.pop()));
}
operators.pop();
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!operators.empty() && hasPrecedence(c, operators.peek())) {
numbers.push(apply(operators.pop(), numbers.pop(), numbers.pop()));
}
operators.push(c);
}
}
while (!operators.empty()) {
numbers.push(apply(operators.pop(), numbers.pop(), numbers.pop()));
}
return numbers.pop();
}
public static int apply(char operator, int b, int a) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) throw new ArithmeticException("除数不能为零");
return a / b;
default:
return 0;
}
}
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')') return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false;
return true;
}
}
```
可以使用该计算器进行除法、加法、减法和乘法,同时支持括号运算。你可以输入这样的表达式进行测试:
```
2 * (3 + 4) - 5 / 2
```
该表达式的结果应该是 12。
阅读全文