题解 | #牛牛计算器#
牛牛计算器
https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace
题目考察的知识点是:
栈的基本操作。
题目解答方法的文字分析:
创建两个栈分别存储操作符和操作数,遍历字符串中的每个元素。主要难点在于括号会改变运算优先级,所以对于括号优先判断,通过计数的方式将括号之间的字符串截取出来,再递归调用函数计算出括号的计算值并压入栈中。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int calculate (String s) {
// write code here
if (s == null || s.length() == 0) {
return 0;
}
int num = 0;
Character preOp = '+';
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
if (Character.isDigit(ch)) {
num = num * 10 + ch - '0';
} else if (ch == '(') {
int j = i, cnt = 0;
while (i < s.length()) {
if (s.charAt(i) == '(') cnt++;
if (s.charAt(i) == ')') cnt--;
if (cnt == 0) {
break;
}
i++;
}
num = calculate(s.substring(j + 1, i));
}
if (!Character.isWhitespace(ch) || i == s.length() - 1) {
if (preOp == '+') {
stack.push(num);
} else if (preOp == '-') {
stack.push(-num);
} else if (preOp == '*') {
int temp = stack.pop() * num;
stack.push(temp);
}
num = 0;
preOp = ch;
}
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
#题解#

