题目

思路
- 表达式转逆波兰表达式
- 逆波兰表达式求值
过程


代码
import java.util.*;
public class Solution {
Map<String, Integer> priority = new HashMap<>();
public int solve (String s) {
priority.put("+", 0);
priority.put("-", 0);
priority.put("*", 1);
priority.put("(", 2);
priority.put(")", 2);
String[] change = change(s);
return calculate(change);
}
public String[] change(String s) {
Stack<String> resstack = new Stack<>();
Stack<String> opstack = new Stack<>();
boolean preNumFlag = false;
String[] exp = s.split("");
for (int i = 0; i < exp.length; i++) {
if (isNum(exp[i])) {
if (!preNumFlag) {
resstack.add(exp[i]);
} else {
String join = resstack.pop() + exp[i];
resstack.add(join);
}
preNumFlag = true;
} else if ("(".equals(exp[i])) {
preNumFlag = false;
opstack.add(exp[i]);
} else if (")".equals(exp[i])) {
preNumFlag = false;
while (!opstack.isEmpty() && !opstack.peek().equals("(")) {
resstack.add(opstack.pop());
}
opstack.pop();
} else {
preNumFlag = false;
while (!opstack.isEmpty() && priority.get(exp[i]) <= priority.get(opstack.peek()) && !opstack.peek().equals("(")) {
resstack.add(opstack.pop());
}
opstack.add(exp[i]);
}
}
while (!opstack.isEmpty()) {
resstack.add(opstack.pop());
}
String[] res = new String[resstack.size()];
for (int i = 0; i < resstack.size(); i++) {
res[i] = resstack.get(i);
}
return res;
}
private boolean isNum(String s) {
if ("+".equals(s) || "-".equals(s) || "*".equals(s) || "(".equals(s) || ")".equals(s)) {
return false;
}
return true;
}
private int calculate(String[] list) {
Stack<Integer> res = new Stack<>();
for (int i = 0; i < list.length; i++) {
String s = list[i];
if ("+".equals(s)) {
res.add(res.pop() + res.pop());
} else if ("-".equals(s)) {
res.add(-res.pop() + res.pop());
} else if ("*".equals(s)) {
res.add(res.pop() * res.pop());
} else {
res.add(Integer.parseInt(String.valueOf(s)));
}
}
return res.pop();
}
}