好长时间没写Java了,用java水一道模拟题。哈希表里面存的是优先级,弹栈时要注意,假如是a/b弹栈弹出的先是b再是a,注意calc函数里面的’-‘跟’/’。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
public class Main {
private static Map<Character, Integer> m = new HashMap<Character, Integer>();
static Stack<Integer> si = new Stack<Integer>();
static Stack<Character> sc = new Stack<Character>();
public static void main(String[] args) {
m.put('+', 1);
m.put('-', 1);
m.put('x', 2);
m.put('/', 2);
int n = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
int res = fun(line);
if (res == 24)
System.out.println("Yes");
else
System.out.println("No");
}
sc.close();
}
private static int fun(String line) {
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) < '0' || line.charAt(i) > '9') {
if (sc.size() > 0 && m.get(line.charAt(i)) <= m.get(sc.peek()))
si.push(calc());
sc.push(line.charAt(i));
} else
si.add(line.charAt(i) - '0');
}
while(!sc.isEmpty())si.add(calc());
return si.pop();
}
private static int calc() {
int a = si.pop();
int b = si.pop();
char op = sc.pop();
if(op=='+')return a+b;
else if(op=='-')return b-a;
else if(op=='x')return a*b;
return b/a;
}
}