题干如下:
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
例如:
输入:
3+2*{1+2*[-4/(8-6)+7]}
输出:
25
思路:使用后缀表达式的方式计算,借鉴http://t.csdnimg.cn/Sv1sW
坑:负数,两位数以及往上
负数解决方案:将-2变成(0-2)的形式
多位数:很简单,遍历到一个数字的时候看它后面还有没有数字
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @className: _5_$
* @author: Lian
* @date: 2023-10-04 17:07
*/
public class _5_4 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Character> operator = new Stack<>();
ArrayList<String> list = new ArrayList<>();
Map<Character, Integer> hashMap = new HashMap<>();
Stack<Double> stack = new Stack<>();
hashMap.put('(', 0);
hashMap.put('-', 1);
hashMap.put('+', 1);
hashMap.put('*', 2);
hashMap.put('/', 2);
StringBuilder str = new StringBuilder(br.readLine().replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')'));
while (true) {
int i;
for (i = 0; i < str.length(); i++) {
if (str.charAt(i) == '-') {
if (i == 0 ||str.charAt(i-1)=='(') {
str.insert(i + 2, ")");
str.insert(i, "(0");
break;
}
}
}
if(i==str.length())
break;
}
char[] chars = str.toString().toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isDigit(chars[i])) {
int j = 0;
while (i+j<chars.length&&Character.isDigit(chars[i + j])) {
j++;
}
list.add(String.copyValueOf(chars, i, j));
i=i+j-1;
continue;
}
if (chars[i] == '(') {
operator.push(chars[i]);
continue;
}
if (chars[i] == ')') {
while (operator.peek() != '(') {
char c = operator.pop();
list.add(String.valueOf(c));
}
operator.pop();
continue;
}
if (operator.isEmpty()) {
operator.push(chars[i]);
continue;
}
while (!operator.isEmpty() && hashMap.get(chars[i]) <= hashMap.get(operator.peek())) {
char c = operator.pop();
list.add(String.valueOf(c));
}
operator.push(chars[i]);
}
while (!operator.isEmpty()) {
list.add(String.valueOf(operator.pop()));
}
for (int i = 0; i < list.size(); i++) {
if (Character.isDigit(list.get(i).charAt(0))) {
stack.push(Double.valueOf(list.get(i)));
continue;
}
double a = stack.pop();
double b = stack.pop();
if (list.get(i).equals("+")) {
stack.push(a + b);
continue;
}
if (list.get(i).equals("*")) {
stack.push(a * b);
continue;
}
if (list.get(i).equals("-")) {
stack.push(b - a);
continue;
}
if (list.get(i).equals("/")) {
stack.push(b / a);
}
}
System.out.printf("%.0f%n", stack.peek());
}
}