【栈】LeetCode 772. 基本计算器 III
题目链接
实现一个基本的计算器来计算简单的表达式字符串。
表达式字符串只包含非负整数,算符 +、-、、/ ,左括号 ( 和右括号 ) 。整数除法需要 向下截断 。
你可以假定给定的表达式总是有效的。所有的中间结果的范围均满足 [-231, 231 - 1]
注意:你不能使用任何将字符串作为表达式求值的内置函数,比如 eval() 。
示例 1:
输入:s = "1+1"
输出:2
示例 2:
输入:s = "6-4/2"
输出:4
示例 3:
输入:s = "2(5+5*2)/3+(6/2+8)"
输出:21
思路
与【栈】LeetCode 227. 基本计算器 II 完全相同
代码
class Solution {
public int calculate(String s) {
// 定义运算符优先级
Map<Character, Integer> map = new HashMap<Character, Integer>(){{
put('+', 1);
put('-', 1);
put('*', 2);
put('/', 2);
put('%', 2);
put('^', 3);
}};
s = s.replaceAll(" ", "");
Stack<Integer> numbers = new Stack<>();
Stack<Character> operators = new Stack<>();
char[] expression = s.toCharArray();
for(int i = 0; i < expression.length; i++){
char c = expression[i];
if(c == '('){
operators.push(c);
}else if(c == ')'){
while(!operators.isEmpty() && operators.peek() != '('){
calc(numbers, operators);
}
operators.pop();
}else if(Character.isDigit(c)){
int u = 0;
int j = i;
while(j < expression.length && Character.isDigit(expression[j])){
u = u * 10 + expression[j] - '0';
j++;
}
numbers.push(u);
i = j - 1;
}else{
if(i > 0 && expression[i - 1] == '('){
numbers.push(0);
}
while(!operators.isEmpty() && operators.peek() != '('){
char prev = operators.peek();
if(map.get(prev) >= map.get(c)){
calc(numbers, operators);
}else{
break;
}
}
operators.push(c);
}
}
while(!operators.isEmpty()){
calc(numbers, operators);
}
return numbers.peek();
}
void calc(Stack<Integer> numbers, Stack<Character> operators){
if(numbers.size() < 2){
return;
}
if(operators.isEmpty()){
return;
}
int second = numbers.pop();
int first = numbers.pop();
char c = operators.pop();
switch(c){
case '+':
numbers.push(first + second);
break;
case '-':
numbers.push(first - second);
break;
case '*':
numbers.push(first * second);
break;
case '/':
numbers.push(first / second);
break;
case '%':
numbers.push(first % second);
break;
case '^':
numbers.push((int)Math.pow(first, second));
break;
}
}
}