题目:定一个逆波兰表达式,求表达式的值。
思路:利用栈的数据结构,遇到符号则出栈两个数字进行运算,运算后重新入栈。
package com.study.core.test2;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author mlj
* @date 2024年03月14日 10:04
*/
public class Test0314 {
public static void main(String[] args) {
String[] tokens = {"3", "0", "-"};
int i = evalRPN(tokens);
System.out.println(i);
}
/**
* 给定一个逆波兰表达式,求表达式的值。
* <p>
* 数据范围:表达式长度满足
*
* @param tokens
* @return int
* @author mlj
* @date 2024/3/14 10:38
*/
public static int evalRPN(String[] tokens) {
// write code here
if (tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
//特殊符号
List<String> list = new ArrayList<>();
list.add("+");
list.add("-");
list.add("*");
list.add("/");
for (String token : tokens) {
int a;
int b;
if (list.contains(token)) {
//注意栈先进后出,需要调换a b 位置
b = stack.pop();
a = stack.pop();
switch (token) {
case "+":
stack.push(a + b);
break;
case "-":
stack.push(a - b);
break;
case "*":
stack.push(a * b);
break;
case "/":
stack.push(a / b);
break;
}
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}