题解 | #牛牛计算器# java
牛牛计算器
https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ public int calculate (String s) { // write code here Stack<Integer> nums = new Stack<>(); Stack<Character> ops = new Stack<>(); int num = 0; char preOp = '+'; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { num = num * 10 + c - '0'; } else if (c == '(') { int j = i, cnt = 0; for (; i < s.length(); i++) { if (s.charAt(i) == '(') cnt++; if (s.charAt(i) == ')') cnt--; if (cnt == 0) break; } num = calculate(s.substring(j + 1, i)); } if (!Character.isWhitespace(c) || i == s.length() - 1) { if (preOp == '+') { nums.push(num); } else if (preOp == '-') { nums.push(-num); } else if (preOp == '*') { int temp = nums.pop() * num; nums.push(temp); } num = 0; preOp = c; } } int res = 0; while (!nums.isEmpty()) { res += nums.pop(); } return res; } }
该代码使用的编程语言是Java。
该题考察的知识点是利用栈(Stack)数据结构实现后缀表达式的计算。后缀表达式是一种不含括号的数学表达式,例如 "2 3 +" 表示 2 + 3。需要遍历给定的字符串数组 tokens,根据运算符进行相应的计算,并将结果压入栈中,最后返回栈顶元素即可。
具体的代码解释如下:
- 创建两个栈,
nums
用于存储操作数,ops
用于存储运算符。 - 初始化变量
num
为0,用于存储当前处理的数字。 - 初始化变量
preOp
为 '+',表示初始状态下的上一个运算符为加号。 - 进入循环,遍历字符串
s
中的每个字符:如果当前字符是数字,则将其转为整数并累加到 num 中。如果当前字符是左括号 (,则进入内循环,找到与之对应的右括号 ) 的位置,并递归调用 calculate 方法对括号内的表达式进行计算,返回结果将赋值给 num。如果当前字符是运算符或者是最后一个字符,则根据上一个运算符 preOp 进行相应的处理:如果 preOp 是加号 +,将 num 压入 nums 栈中。如果 preOp 是减号 -,将 -num 压入 nums 栈中。如果 preOp 是乘号 *,将栈顶元素弹出,并与 num 相乘后再压入 nums 栈中。将 num 重置为0,并更新 preOp 为当前字符。 - 循环结束后,将
nums
栈中的所有元素累加起来,得到最终的计算结果。 - 返回计算结果。