作者:那一世我给不了你的温柔 | 来源:互联网 | 2023-06-08 05:29
原题网址:https://leetcode.com/problems/basic-calculator-ii/
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces
. The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
思路:和上一道Basic Calculator题目相似,使用栈解决运算优先级的问题。
public class Solution {
public int calculate(String s) {
char[] sa = s.toCharArray();
Expression[] expressiOns= new Expression[4];
int[] operands = new int[4];
int size = 0;
for(int i=0; i= '0' && sa[i] <= '9') {
// 遇到数字
int num = sa[i] - '0';
// 完整读取数字
while (i= '0' && sa[i+1] <= '9') num = num*10 + (sa[++i]-'0');
if (size > 0 && expressions[size-1] == Expression.MULTIPLY) {
// 如果当前的运算符为乘法,则立即完成运算
operands[size-2] *= num;
size --;
} else if (size > 0 && expressions[size-1] == Expression.DIVIDE) {
// 如果当前的运算符为除法,则立即完成运算
operands[size-2] /= num;
size --;
} else {
// 当前运算符为加法或减法,要等到下一个运算符才能决定
expressions[size] = Expression.OPERAND;
operands[size] = num;
size ++;
}
} else if (sa[i] == '+' || sa[i] == '-') {
if (size > 2) {
// 当前运算符为加法、减法,可以检查前面是否有为完成运算的加减法
if (expressions[size-2] == Expression.PLUS) {
operands[size-3] += operands[size-1];
size -= 2;
} else if (expressions[size-2] == Expression.MINUS) {
operands[size-3] -= operands[size-1];
size -= 2;
}
}
// 加减号入栈
if (sa[i] == '+') {
expressions[size++] = Expression.PLUS;
} else {
expressions[size++] = Expression.MINUS;
}
} else {
// sa[i] == '*' || sa[i] == '/'
// 乘除号入栈
if (sa[i] == '*') expressions[size++] = Expression.MULTIPLY;
else expressions[size++] = Expression.DIVIDE;
}
}
if (size > 1) {
if (expressions[1] == Expression.PLUS) {
operands[0] += operands[2];
} else {
operands[0] -= operands[2];
}
size = 1;
}
return operands[0];
}
}
enum Expression {OPERAND, PLUS, MINUS, MULTIPLY, DIVIDE};