题目描述
blablabla
样例
blablabla
java 代码
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
public static Stack<Long> num = new Stack<>();
public static Stack<Character> op = new Stack<>();
public static HashMap<Character , Integer > pr = new HashMap<Character , Integer >()
{{ put('+',1);
put('-',1);
put('*',2);
put('/',2);}};
public static void eval(){
long b = num.peek();num.pop();//先读b再读a!
long a = num.peek();num.pop();
char ops = op.peek();op.pop();
long x = 0;
if(ops=='+') x=a+b;
if(ops=='-') x=a-b;
if(ops=='*') x=a*b;
if(ops=='/') x=a/b;
num.push(x);
}
public static void main (String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
for(int i = 0 ; i < str.length() ; i++ ){
char t = str.charAt(i);
if(Character.isDigit(t)){
int j = i,x=0;
while(j < str.length() && Character.isDigit(str.charAt(j))){
x = x*10 + (str.charAt(j++) - '0');
}
num.push ((long) x) ;
i = j-1;
}
else if (t == '(') {op.push(t);}
else if (t == ')'){
while(op.size()!=0 && op.peek() != '(') eval();
op.pop();
}
else {
while(op.size()!=0 && op.peek() != '('&& pr.get(op.peek()) >= pr.get(t)) eval();//op.peek()可能是"("
op.push(t);
}
}
while(op.size() != 0) eval();
System.out.println(num.peek());
}
}
”(” 写成优先级0,放到map中, 就不用特别判断了
写起来真费劲
代码里标注了比较坑的两个地方