逆波兰表达式
import java.util.Stack;
/**
* @author: seh
* @date: 2020/10/30 14:01
* @version: 1.0
*/
public class demo1 {
public static void main(String[] args) {
String array[]={"2","3","4","+","*"};
Solution2 solution2=new Solution2();
System.out.println(solution2.findNumber(array));
}
}
class Solution2{
private boolean isOperator(String index) {
return "+-*/".contains(index);
}
private int calculate(Integer right, Integer left, String operator) {
switch (operator){
case "+":return right+left;
case "-":return right-left;
case "*":return right*left;
default: return right/left;
}
}
public int findNumber(String []nums){
Stack<Integer> stack=new Stack<Integer>();
for (String index : nums) {
if(isOperator(index)){
Integer right = stack.pop();
Integer left = stack.pop();
stack.push(calculate(right,left,index));
}else{
// 如果是数字,则压入栈中
stack.push(Integer.parseInt(index));
}
}
return stack.pop();
}
}
利用数据结构中的栈的思想,对一个表达式进行处理,使其运算结果满足逆波兰表达式(后缀表达式)