1 题目链接
2 题目要求
描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*“和”/",被操作数可能是整数或其他表达式
["20", "10", "+", "30", "*"] -> ((20 + 10) * 30) -> 900
["40", "130", "50", "/", "+"] -> (40 + (130 / 50)) -> 42
示例
输入:["20","10","+","30","*"]
返回值:900
3 代码思路
题目所有运算符都是二元运算符,且后缀表达式使用数组存储,相较于字符串存储更加简单一些。
解题选用Stack数据结构。数组中只有两种数据:数字和符号。对数组进行遍历,如果遍历到的数据是数字,将数字加入栈。如果遍历到的是符号,那么将栈中数据弹出两个,计算之后的结果重新加入栈。最终栈中只剩下一个数据,就是最终的答案。
4 代码实现
public class Solution {
public int evalRPN (String[] tokens) {
Stack<Integer> stack = new Stack();
// 遍历数组,对符号或者数据进行不同的操作
for(int i = 0; i < tokens.length; i++){
// 如果是数字,进栈
try{
int num = Integer.parseInt(tokens[i]);
stack.add(num);
}catch(Exception e){
// 不是数字,栈中弹出栈顶和次栈顶,进行计算
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(caculate(num2, num1, tokens[i]));
}
}
// 返回最终的结果
return stack.pop();
}
// 计算
public int caculate(int a,int b,String c){
switch(c){
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
return 0;
}
}
5 知识补充
明天面试,苟求一下速度,补充内容放在面试之后
5.1 switch支持的数据类型
5.2 中序转换为后序表达式
5.3 字符串类型和基本类型的相互转换
5.4 Stack基本操作
https://blog.csdn.net/weixin_39963192/article/details/115053147