做这题之前得需要明白什么是波兰表达式,和逆波兰表达式。
其实就是把我们眼睛看到的字符串转换成电脑可以识别计算的字符串,这个是在数据结构一书中有案例的,不懂的小伙伴可以去了解一下。
解题思路如下:
- 创建一个栈用来存放这些数据。
- 便利数组的数据。
- 如果是数字,直接入栈。
- 如果是字符,取出栈内的数据,然后根据字符进行操作。
import java.util.Deque; import java.util.LinkedList; /** * @author xienl * @description 逆波兰表达式求值 * @date 2022/5/24 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); // String[] tokens = {"2","1","+","4","*"}; String[] tokens = {"2","0","+"}; System.out.println(solution.evalRPN(tokens)); } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { // 存放数字结果的栈 Deque<Integer> stack = new LinkedList<>(); for (String str : tokens) { if ("+".equals(str) || "-".equals(str) || "*".equals(str) || "/".equals(str)){ calculation(stack, str); } else { stack.push(Integer.parseInt(str)); } } return stack.peek(); } /** * 计算器 * @param stack 存放数字的栈 * @param str 存放计算字符 */ private void calculation(Deque<Integer> stack, String str){ Integer num1 = stack.pop(); Integer num2 = stack.pop(); switch (str){ case "+": stack.push(num1 + num2); break; case "-": stack.push(num2 - num1); break; case "*": stack.push(num1 * num2); break; case "/": stack.push(num2 / num1); break; default: } } }