原题链接
用java练练手。
遇到括号递归进行处理,就是传递引用比价麻烦,这里是传递了个一个数字的数组,以后想到优雅的做法在再补充。
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++) {
String s = sc.nextLine();
if (judge(s))
System.out.println("Y");
else
System.out.println("N");
}
sc.close();
}
private static boolean judge(String s) {
int idx = s.indexOf('=');
HashMap<String, Integer> hm1 = work(s.substring(0, idx));
HashMap<String, Integer> hm2 = work(s.substring(idx + 1, s.length()));
return hm1.equals(hm2);
}
private static HashMap<String, Integer> work(String str) {
HashMap<String, Integer> res = new HashMap<String, Integer>();
String[] item = str.split("\\+");
for (int i = 0; i < item.length; i++) {
int j = 0;
while (j < item[i].length() && Character.isDigit(item[i].charAt(j)))
j++;
int cnt = 1;
if (j > 0) {
cnt = Integer.parseInt(item[i].substring(0, j));
item[i] = item[i].substring(j);
}
HashMap<String, Integer> hm = work_item(item[i], new int[] { 0 });
for (String s : hm.keySet()) {
if (res.containsKey(s))
res.put(s, res.get(s) + hm.get(s) * cnt);
else
res.put(s, hm.get(s) * cnt);
}
}
return res;
}
private static HashMap<String, Integer> work_item(String s, int[] num) {
HashMap<String, Integer> res = new HashMap<String, Integer>();
while (num[0] < s.length()) {
switch (s.charAt(num[0])) {
case '(':
num[0]++;
HashMap<String, Integer> hm = work_item(s, num);
int cnt = 1;
int x = num[0];
while (num[0] < s.length() && Character.isDigit(s.charAt(num[0])))
num[0]++;
if (num[0] > x)
cnt = Integer.parseInt(s.substring(x, num[0]));
for (String t : hm.keySet()) {
if (res.containsKey(t))
res.put(t, res.get(t) + hm.get(t) * cnt);
else
res.put(t, hm.get(t) * cnt);
}
break;
case ')':
num[0]++;
return res;
default:
int j = num[0] + 1;
while (j < s.length() && Character.isLowerCase(s.charAt(j)))
j++;
String str = s.substring(num[0], j);
int count = 1;
int e = j;
while (e < s.length() && Character.isDigit(s.charAt(e)))
e++;
if (e > j)
count = Integer.parseInt(s.substring(j, e));
num[0] = e;
if (res.containsKey(str))
res.put(str, res.get(str) + count);
else
res.put(str, count);
break;
}
}
return res;
}
}