逆波兰表达式
- 1.题目
- 2.思路
- 3.代码
1.题目
2.思路
3.代码
class Solution {
public int evalRPN(String[] tokens) {
//创建一个栈
Stack<Integer> stack = new Stack<>();
//对字符串数组进行遍历
for(String x : tokens){
//分数操作符和操作数两种情况,我们得判断
//一下字符串是操作数还是操作符
//如果是数字
if(!isOperation(x)){
stack.push(Integer.parseInt(x));
}
else{
//先右操作数,后左操作数
int num2 = stack.pop();
int num1 = stack.pop();
switch(x){
case "+":
stack.push(num1+num2);
break;
case "-":
stack.push(num1-num2);
break;
case "*":
stack.push(num1*num2);
break;
case "/":
stack.push(num1/num2);
break;
}
}
}
return stack.pop();
}
private boolean isOperation(String x){
if(x.equals("+")||x.equals("-")||x.equals("*")||x.equals("/")){
return true;
}
return false;
}
}