字符串中四则运算表达式求值

发布时间 2023-04-12 21:12:33作者: MarkLeeBYR

字符串内容:1 + 2 * 5 - 6 / 2

写代码求出该字符串的值

 

class Main {
private static final Map<String,Integer> map = new HashMap<>();

private void initMap() {
map.put("+", 1);
map.put("-", 1);
map.put("*", 2);
map.put("/", 2);

}

public int cal(String str) {
if (str == null || str.length() == 0) {
return 0;
}

initMap();

Stack<Integer> numStack = new Stack<>(); //存储计算结果
Stack<String> opStack = new Stack<>(); // 存储运算符符
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == ' ') { // 空字符,跳过
continue;
}
if (ch >= '0' && ch <= '9') { //是数字,需要加到sb的末尾
sb.append(ch);
} else {
if (sb.length() > 0) {
numStack.push(Integer.valueOf(sb.toString()));
sb.delete(0, sb.length());
}
String op = String.valueOf(ch);
if (opStack.isEmpty()) {
opStack.push(op);
} else {
while (!opStack.isEmpty()) {
if (helper(op, opStack.peek())){ // 比较计算运算符的优先级
calFun(numStack, opStack); // 计算结果
if (opStack.isEmpty()){
opStack.push(op);
break;
}
} else {
opStack.push(op);
break;
}
}
}
}
}

if (sb.length() > 0) {
numStack.push(Integer.valueOf(sb.toString()));
}

while (!opStack.empty()){
calFun(numStack, opStack);
}
return numStack.pop();
}