224. [栈]基本计算器
224. 基本计算器
由于题目中仅有 +、-、(、) ,在处理 - 时,将其看作是原数 (-1)*operand,那么剩余表达式中就只有 + 运算符,而 + 运算符是遵循结合律的。
- 每当我们遇到
+或-运算符时,我们首先将表达式求值到左边,然后将正负符号保存到下一次求值。 - 如果字符是左括号
(,我们将迄今为止计算的结果和符号添加到栈上,然后重新开始进行计算,就像计算一个新的表达式一样。 - 如果字符是右括号
),则首先计算左侧的表达式。则产生的结果就是刚刚结束的子表达式的结果。如果栈顶部有符号,则将此结果与符号相乘。
// 执行用时: 9 ms , 在所有 Java 提交中击败了 85.53% 的用户
// 内存消耗: 38.8 MB , 在所有 Java 提交中击败了 93.28% 的用户
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
int operand = 0;
int result = 0;
int sign = 1;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
operand = operand * 10 + (ch - '0');
} else if (ch == '+'){
result += sign * operand;
sign = 1;
operand = 0;
} else if (ch == '-'){
result += sign * operand;
sign = -1;
operand = 0;
} else if (ch == '('){
stack.push(result);
stack.push(sign);
sign = 1;
result = 0;
} else if (ch == ')'){
result += sign * operand;
result *= stack.pop();
result += stack.pop();
operand = 0;
}
}
return result + operand * sign;
}
}

浙公网安备 33010602011771号