package com.zmz.algorithm.stackQueue;
import java.util.Stack;
/**
* @author 张明泽
* Create by 2022/5/31 23:04
* 逆波兰表达式求值
* LeetCode-150
*/
public class EvaluateInverseExpression {
public static void main(String[] args) {
String[] tokens = {"4","13","5","/","+"};
int result = evalRPN(tokens);
System.out.println(result);
}
public static int evalRPN(String[] str) {
Stack<Integer> stack = new Stack<>();
for (String s : str) {
if (s.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (s.equals("-")) {
int temp = stack.pop();
stack.push(stack.pop() - temp);
} else if (s.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (s.equals("/")) {
int temp = stack.pop();
stack.push(stack.pop() / temp);
}
else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
最后修改:2022 年 06 月 02 日 10 : 23 AM
© 允许规范转载